#146

LRU Cache

specialist · 915 · lc medium +31 · 46.9% accepted · 22,982 likes · top 31%

play →

Description

Build a data structure that implements a Least Recently Used (LRU) cache.

Implement the LRUCache class:

- LRUCache(int capacity) initializes the cache with the given positive capacity.

- int get(int key) returns the value for key if it exists in the cache; otherwise returns -1.

- void put(int key, int value) inserts or updates a key-value pair. When capacity is exceeded, the least recently used item is evicted.

Both get and put must run in O(1) average time complexity.

Example 1:

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]

Example 2:

Explanation
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache is {1=1}
lRUCache.put(2, 2); // cache is {1=1, 2=2}
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.get(2); // returns -1 (not found)
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(1); // return -1 (not found)
lRUCache.get(3); // return 3
lRUCache.get(4); // return 4

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16