Design and implement a data structure for Least Recently Used (LRU) cache. 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.
Follow up:
Could you do both operations in O(1) time complexity?
基本思想在于用双向链表来进行LRU的操作。
public class LRUCache {
private class Node{
int key;
int value;
Node prev;
Node next;
public Node(int key, int value){
this.key = key;
this.value = value;
}
}
Node head;
Node tail;
int capacity;
int size;
Map<Integer, Node> map;
public LRUCache(int capacity) {
head = new Node(0,0);
head.next = tail;
tail = new Node(0,0);
tail.prev = head;
this.capacity = capacity;
size = 0;
map = new HashMap<>(capacity);
}
public int get(int key) {
if(map.containsKey(key)){
Node tmp = map.get(key);
tmp.prev.next = tmp.next;
tmp.next.prev = tmp.prev;
tail.prev.next = tmp;
tmp.prev = tail.prev;
tmp.next = tail;
tail.prev = tmp;
return tmp.value;
}else{
return -1;
}
}
public void put(int key, int value) {
if(!map.containsKey(key)){
if(size == capacity){
int tmpkey = head.next.key;
head.next = head.next.next;
head.next.prev = head;
map.remove(tmpkey);
size--;
}
Node tmp = new Node(key,value);
map.put(key,tmp);
tail.prev.next = tmp;
tmp.prev = tail.prev;
tmp.next = tail;
tail.prev = tmp;
size++;
}else{
Node tmp = map.get(key);
tmp.value = value;
tmp.prev.next = tmp.next;
tmp.next.prev = tmp.prev;
tail.prev.next = tmp;
tmp.prev = tail.prev;
tmp.next = tail;
tail.prev = tmp;
}
}
}
/**
* 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);
*/