leetcode 146. 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
其实最主要还是要单独写一个DListNode 的class出来,然后把add和remove方法都单独写好。
注意用了key-node这样一个哈希表,便于快速将argument里面的key定位到相应的含有键值对的node上。其实这个套路很像61B的pj3.
class LRUCache { class DListNode { int key; int value; DListNode prev; DListNode next; } public void addNode(DListNode node) { node.prev = head; node.next = head.next; head.next.prev = node; head.next = node; } public void removeNode(DListNode node) { node.prev.next = node.next; node.next.prev = node.prev; } public void moveToHead(DListNode node) { this.removeNode(node); this.addNode(node); } private Map<Integer,DListNode> ht = new HashMap<Integer,DListNode>(); int c = 0; int capacity; DListNode head,tail; public LRUCache(int capacity) { this.capacity = capacity; head = new DListNode(); tail = new DListNode(); head.next = tail; head.prev = null; tail.prev = head; tail.next = null; } public int get(int key) { DListNode node = ht.get(key); if(node == null) { return -1; } this.moveToHead(node); return node.value; } public void put(int key, int value) { DListNode node = ht.get(key); if(node == null) { DListNode n = new DListNode(); n.key = key; n.value = value; this.addNode(n); ht.put(key,n); c++; if(c>capacity) { ht.remove(tail.prev.key); this.removeNode(tail.prev); c--; } }else { node.value = value; this.moveToHead(node); } } }