You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
3
+
4
+
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
5
+
put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
6
+
7
+
The cache is initialized with a positive capacity.
8
+
9
+
Follow up:
10
+
Could you do both operations in O(1) time complexity?
11
+
12
+
Example:
13
+
14
+
LRUCache cache = new LRUCache( 2 /* capacity */ );
15
+
16
+
cache.put(1, 1);
17
+
cache.put(2, 2);
18
+
cache.get(1); // returns 1
19
+
cache.put(3, 3); // evicts key 2
20
+
cache.get(2); // returns -1 (not found)
21
+
cache.put(4, 4); // evicts key 1
22
+
cache.get(1); // returns -1 (not found)
23
+
cache.get(3); // returns 3
24
+
cache.get(4); // returns 4
25
+
"""
26
+
27
+
28
+
classLRUCache:
29
+
30
+
def__init__(self, capacity: int):
31
+
self.hmap=collections.OrderedDict()
32
+
self.capacity=capacity
33
+
34
+
defget(self, key: int) ->int:
35
+
ifkeynotinself.hmap.keys():
36
+
return-1
37
+
value=self.hmap.pop(key)
38
+
self.hmap[key] =value
39
+
returnvalue
40
+
41
+
defput(self, key: int, value: int) ->None:
42
+
ifkeyinself.hmap.keys():
43
+
self.hmap.pop(key)
44
+
else:
45
+
iflen(self.hmap) >=self.capacity:
46
+
self.hmap.popitem(last=False)
47
+
self.hmap[key] =value
48
+
49
+
# Your LRUCache object will be instantiated and called as such:
0 commit comments