Design and implement a data structure for . It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
The cache is initialized with a positive capacity.
Follow up: Could you do both operations in O(1) time complexity?
classNode{ int key; int val; Node next; Node prev; publicNode(int key, int val){ this.key = key; this.val = val; } publicvoidinsertNext(Node n){ if (next == null) { next = n; n.prev = this; } else { n.next = next; next.prev = n; next = n; n.prev = this; } } publicvoidremoveNext(){ if (next == null) { return; } if (next.next == null) { next.prev = null; next = null; return; } Node nn = next.next; next.prev = null; next.next = null; next = nn; nn.prev = this; } } Node dummy; Node tail; Map<Integer, Node> map; int size; int cap; publicLRUCache(int capacity){ cap = capacity; size = 0; dummy = new Node(0, 0); tail = new Node(0, 0); tail.prev = dummy; dummy.next = tail; map = new HashMap<>(); } publicintget(int key){ if (!map.containsKey(key)) { return -1; } else { int val = map.get(key).val; put(key, val); return val; } } publicvoidput(int key, int value){ if (map.containsKey(key)) { Node n = map.get(key); n.val = value; n.prev.removeNext(); dummy.insertNext(n); } else { if (size >= cap) { Node n = tail.prev; map.remove(n.key); tail.prev.prev.removeNext(); } else { size++; } dummy.insertNext(new Node(key, value)); map.put(key, dummy.next); } } }
/** * Your LRUCache object will be instantiated and called as such: * LRUCache obj = new LRUCache(capacity); * int param_1 = obj.get(key); * obj.put(key,value); */