LRU Cache
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?
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
用单链表 模拟。只要动了,。就把他移到最后
map记录的是要记录的node的key和这个node之前的那个node。已便于移动,
class LRUCache {
class Node{
public int key, val;
public Node next;
public Node(int key, int value){
this.key = key;
this.val = value;
this.next = null;
}
}
private int capacity, size;
private Node dummy,tail;
private Map<Integer,Node> map;
public LRUCache(int capacity) {
this.capacity = capacity;
size = 0;
map = new HashMap<>();
this.dummy = new Node(0,0);
tail = dummy;
}
public void moveToTail(int key){
Node prev = map.get(key);
Node cur = prev.next;
if(tail == cur){
return;
}
//cur != tail. 说明prev的next的next不为空
prev.next = prev.next.next;
tail.next = cur;
cur.next = null;
if(prev.next != null)
map.put(prev.next.key,prev);
map.put(key,tail);
tail = cur;
}
public int get(int key) {
if(!map.containsKey(key)){
return -1;
}
moveToTail(key);
return tail.val;
}
public void put(int key, int value) {
//get method move key to end
if(get(key) != -1){
Node prev = map.get(key);
prev.next.val = value;
return;
}
if(size < capacity){
Node n = new Node(key,value);
size++;
tail.next = n;
map.put(key,tail);
tail = n;
return;
}
Node LRU = dummy.next;
map.remove(LRU.key);
LRU.key = key;
LRU.val = value;
map.put(key,dummy);
moveToTail(key);
}
}
/**
* 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);
*/
Last updated