Skip to content

Commit 7e99e3f

Browse files
committed
update 146
1 parent a60dc3d commit 7e99e3f

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Hashing/146. LRU Cache.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Learning how to use OrderedDict() and its popitem(last=False) function to pop the first in element
2+
3+
4+
class LRUCache:
5+
6+
def __init__(self, capacity: int):
7+
self.capacity = capacity
8+
self.dict = collections.OrderedDict()
9+
10+
11+
def get(self, key: int) -> int:
12+
if key in self.dict:
13+
v = self.dict[key]
14+
del self.dict[key]
15+
self.dict[key] = v
16+
return self.dict[key]
17+
else:
18+
return -1
19+
20+
def put(self, key: int, value: int) -> None:
21+
if key in self.dict:
22+
del self.dict[key]
23+
self.dict[key] = value
24+
25+
else:
26+
if len(self.dict) >= self.capacity:
27+
self.dict.popitem(last=False)
28+
self.dict[key] = value
29+
30+
31+
# Your LRUCache object will be instantiated and called as such:
32+
# obj = LRUCache(capacity)
33+
# param_1 = obj.get(key)
34+
# obj.put(key,value)

0 commit comments

Comments
 (0)