#460
LFU Cache
candidate master · 1460 · lc hard +32 · 48.7% accepted · 6,314 likes · top 35%
Description
Build a Least Frequently Used (LFU) cache with a fixed maximum capacity.
Implement the LFUCache class:
- LFUCache(int capacity) Initializes the cache with the given capacity.
- int get(int key) Returns the cached value for key, or -1 if the key is absent.
- void put(int key, int value) Inserts or updates key. When the cache is at capacity and a new key is needed, evict the least frequently used key; break frequency ties by evicting the least recently used among those.
Every key's use count starts at 1 on insertion and grows with each get or put. Both operations must achieve O(1) average time complexity.
Example 1:
Input
["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]
Output
[null, null, null, 1, null, -1, 3, null, -1, 3, 4]
Example 2:
Explanation
// cnt(x) = the use counter for key x
// cache=[] will show the last used order for tiebreakers (leftmost element is most recent)
LFUCache lfu = new LFUCache(2);
lfu.put(1, 1); // cache=[1,_], cnt(1)=1
lfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1
lfu.get(1); // return 1
// cache=[1,2], cnt(2)=1, cnt(1)=2
lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.
// cache=[3,1], cnt(3)=1, cnt(1)=2
lfu.get(2); // return -1 (not found)
lfu.get(3); // return 3
// cache=[3,1], cnt(3)=2, cnt(1)=2
lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.
// cache=[4,3], cnt(4)=1, cnt(3)=2
lfu.get(1); // return -1 (not found)
lfu.get(3); // return 3
// cache=[3,4], cnt(4)=1, cnt(3)=3
lfu.get(4); // return 4
// cache=[4,3], cnt(4)=2, cnt(3)=3
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16