Skip to content

Commit 7265996

Browse files
committed
solution added.
1 parent 4178c2a commit 7265996

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
"""
2+
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+
class LRUCache:
29+
30+
def __init__(self, capacity: int):
31+
self.hmap = collections.OrderedDict()
32+
self.capacity = capacity
33+
34+
def get(self, key: int) -> int:
35+
if key not in self.hmap.keys():
36+
return -1
37+
value = self.hmap.pop(key)
38+
self.hmap[key] = value
39+
return value
40+
41+
def put(self, key: int, value: int) -> None:
42+
if key in self.hmap.keys():
43+
self.hmap.pop(key)
44+
else:
45+
if len(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:
50+
# obj = LRUCache(capacity)
51+
# param_1 = obj.get(key)
52+
# obj.put(key,value)

0 commit comments

Comments
 (0)