← 返回 linkedin 的题目列表Implement LRU Cache
类型:online_judge
Design and implement a data structure for LRU (Least Recently Used) cache. It should support the following operations: get and put. get(key) - Get the value (will always be 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. Implement the LRUCache class with optimal time complexity O(1).
Input:
2
put 1 1
put 2 2
get 1
put 3 3
get 2
put 4 4
get 1
get 3
get 4
Output:
1
-1
-1
3
4
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