← 返回 bytedance 的题目列表Design A Simple LRUCaché
类型:online_judge
bytedance
Design and implement a data structure to simulate an LRU (Least Recently Used) Cache that supports get and put operations. You need to implement the following functionalities:
LRUCache(int capacity): Initializes the LRU cache with a positive integer capacity.
int get(int key): Returns the value of the key if the key exists in the cache, otherwise returns -1.
void put(int key, int value): Sets the value of the key in the cache. If the key already exists, update the value. If the cache has reached its capacity, remove the least recently used item before inserting a new one.
Constraints
All get and put operations' keys and values will be integers.
The operations get and put will be called at most 1000 times each.
Example
cache = LRUCache(2);
cache.put(1,1);
cache.put(2,2);
print(cache.get(1)) # returns 1
cache.put(3,3); # evicts key 2
print(cache.get(2)) # returns -1 (not found)
cache.put(4,4); # evicts key 1
print(cache.get(1)) # returns -1 (not found)
print(cache.get(3)) # returns 3
print(cache.get(4)) # returns 4
Example
Input
5:[]