Problem
Design a class LRUCache that holds at most capacity key-value pairs and, when it is full, throws out the least recently used key.
- LRUCache(capacity) creates an empty cache.
- get(key) returns the value for key, or -1 if it is not there. A successful get counts as using the key.
- put(key, value) inserts or updates the key, which also counts as using it. If this adds a new key and the cache is already full, first remove the key that was used longest ago.
Both get and put must run in O(1) average time.
Example 1
cache = LRUCache(2)
Example 2
put(1, 1); put(2, 2)
Example 3
- Input
- get(1)
- Output
- 1
- Why
- 1 is now the most recent
Example 4
put(3, 3) (full: evicts 2, the least recent)
Example 5
- Input
- get(2)
- Output
- -1
Example 6
put(4, 4) (evicts 1)
Example 7
- Input
- get(1)
- Output
- -1
Example 8
- Input
- get(3)
- Output
- 3
Example 9
- Input
- get(4)
- Output
- 4
Constraints
1 <= capacity <= 30000 <= key <= 10^40 <= value <= 10^5At most 2 * 10^5 calls to get and put.