Loading...
Loading...
Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.
An LRU cache evicts the least recently used item when the cache reaches its capacity. "Recently used" means either read (get) or written (put).
Implement the LRUCache class:
LRUCache(int capacity) — Initialize the cache with a positive capacity.int get(int key) — Return the value of the key if it exists, otherwise return -1. Accessing a key marks it as recently used.void put(int key, int value) — Insert or update the key-value pair. If the cache is at capacity before inserting a new key, evict the least recently used key first.Both get and put must run in O(1) average time complexity.
You will receive a list of operations and their arguments:
["LRUCache", "put", "put", "get", ...][[capacity], [key, val], [key, val], [key], ...]Return a list of results corresponding to each operation. The constructor (LRUCache) returns null.
Input:
ops = ["LRUCache","put","put","get","put","get","put","get","get","get"]
args = [[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]
Explanation:
put(1,1) → cache: {1:1}put(2,2) → cache: {1:1, 2:2}get(1) → returns 1; key 1 is now most recently used.put(3,3) → capacity exceeded, evict LRU key (key 2); cache: {1:1, 3:3}get(2) → returns -1 (evicted)put(4,4) → evict LRU key (1); cache: {3:3, 4:4}get(1) → -1, get(3) → 3, get(4) → 41 <= capacity <= 3000 0 <= key <= 10^4 0 <= value <= 10^5 At most 2 * 10^5 calls will be made to get and put
get: move the accessed node to the head.put: if the key exists, update and move to head. If new and at capacity, remove the tail node before inserting at head.