Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
Implement the LRUCache class:
LRUCache(int capacity)— Initialize the LRU cache with positive sizecapacity.int get(int key)— Return the value of thekeyif it exists, otherwise return-1.void put(int key, int value)— Update the value of thekeyif it exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds thecapacityfrom this operation, evict the least recently used key.
The functions get and put must each run in O(1) average time complexity.
Example
Input:
["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1,1], [2,2], [1], [3,3], [2], [4,4], [1], [3], [4]]
Output: [null, null, null, 1, null, -1, null, -1, 3, 4]
Constraints
1 <= capacity <= 30000 <= key <= 10⁴0 <= value <= 10⁵- At most
2 * 10⁵calls will be made togetandput.
How the tests work: each test is a sequence of calls.
operations[i]is the method called witharguments[i]; the first entry constructs the class. The expected output lists what every call returns —nullfor the constructor and for methods that return nothing.