146. LRU Cache - Hard
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
HashMap + Double LinkedList
首先定義一個Node類,用來構建double linked list,包括key, val, next, prev。兩個引數count, capacity,count用來給cache裡的元素計數。LRUcache初始化的時候,還要定義兩個dummy Node,head和tail,方便取和放連結串列首(head.next)、尾(tail.prev)的元素。
get:如果map中存在該key,從map中取出node,儲存這個node對應的value,在連結串列中刪掉這個節點,再把這個節點插入到連結串列頭部。如果map中不存在該key,返回-1。
put:根據map中有無該key,分兩種情況
1. map中無key。根據新的(key, value)新建一個node,把node放進map裡。如果沒有超過容量,把當前node放到double linked list的頭部,並且count增加1;如果超過容量,刪除連結串列尾部的節點(注意除了連結串列裡,map裡也要刪除!),並把當前node插入到頭部。
2. map中有key。從map中取出node,並賦值為當前value,在連結串列中刪掉這個節點,再把這個節點插入到連結串列頭部。
刪除節點 和 把節點插入到連結串列頭部 可以用兩個輔助函式來表示。
時間:O(1),空間:O(N)
class LRUCache { class Node { int key, val; Node next, prev; public Node(int key, int val) { this.key = key; this.val = val; } } HashMap<Integer, Node> map; Node head, tail; int count, capacity; public LRUCache(int capacity) { this.capacity = capacity; count = 0; map = new HashMap<>(); head = new Node(0, 0); tail = new Node(0, 0); head.next = tail; head.prev = null; tail.next = null; tail.prev = head; } private void deleteNode(Node node) { node.prev.next = node.next; node.next.prev = node.prev; } private void addToHead(Node node) { head.next.prev = node; node.next = head.next; head.next = node; node.prev = head; } public int get(int key) { if(map.containsKey(key)) { Node node = map.get(key); int val = node.val; deleteNode(node); addToHead(node); return val; } return -1; } public void put(int key, int value) { if(map.containsKey(key)) { Node node = map.get(key); node.val = value; deleteNode(node); addToHead(node); } else { Node node = new Node(key, value); map.put(key, node); if(count < capacity) { addToHead(node); count++; } else { map.remove(tail.prev.key); deleteNode(tail.prev); addToHead(node); } } } } /** * 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); */