Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:
getandput.
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.Follow up:
Could you do both operations inO(1)time complexity?Example:
LRUCache cache = new LRUCache( 2 /* capacity */ ); cache.put(1, 1); cache.put(2, 2); cache.get(1); // returns 1 cache.put(3, 3); // evicts key 2 cache.get(2); // returns -1 (not found) cache.put(4, 4); // evicts key 1 cache.get(1); // returns -1 (not found) cache.get(3); // returns 3 cache.get(4); // returns 4
class LRUCache {
class Node{
Node pre;
Node next;
int key;
int val;
public Node(int key, int val) {
this.key = key;
this.val = val;
}
}
int capacity;
Map<Integer, Node> map;
Node head;
Node tail;
public LRUCache(int capacity) {
this.capacity = capacity;
this.map = new HashMap<>();
this.head = new Node(-1, -1);
this.tail = new Node(-1, -1);
head.next = tail;
tail.pre = head;
}
public int get(int key) {
if(!map.containsKey(key)) return -1;
Node cur = map.get(key);
cur.pre.next = cur.next;
cur.next.pre = cur.pre;
tail.pre.next = cur;
cur.pre = tail.pre;
tail.pre = cur;
cur.next = tail;
return map.get(key).val;
}
public void put(int key, int value) {
if (get(key) != -1) { //map里已经存在这个key,那就把value更新一下就好
//且这里get操作了一次,下面在这个if里不用再移动
Node cur = map.get(key);
cur.val = value;
return;
}
if(map.size() >= capacity) { //map size大于capacity时候,要在node链表里移除最头上的node,同时移除map里面对应的那个key
map.remove(head.next.key);
head.next = head.next.next;
head.next.pre = head;
}
Node node = new Node(key, value); //node里面存的key的值和map里面key值相同
map.put(key, node);
tail.pre.next = node;
node.pre = tail.pre;
tail.pre = node;
node.next = tail;
}
}