← 返回 amazon 的题目列表LRU Cache
类型:online_judge
Implement the LRU (Least Recently Used) cache mechanism. You need to support get and put operations.
get(key) - Get the value (always positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present. When the cache reaches its capacity, it should invalidate the least recently used item before inserting a new item.
Please construct a class to fulfill the functionality above, initialize the cache with a positive integer as capacity.
Example
LRUCache cache = new LRUCache(2);
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
Constraints
1 <= capacity <= 3000
0 <= key <= 10000
0 <= value <= 10000
Up to 3 * 10^4 calls will be made to get and put
Example
Input
2
put 1 1
put 2 2
get 1
put 3 3
get 2
put 4 4
get 1
get 3
get 4