-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0146_LRU_Cache.py
More file actions
31 lines (25 loc) · 828 Bytes
/
0146_LRU_Cache.py
File metadata and controls
31 lines (25 loc) · 828 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class LRUCache:
def __init__(self, capacity: int):
self.size = 0
self.capacity = capacity
self.stack = collections.OrderedDict()
def get(self, key: int) -> int:
if key in self.stack:
self.stack.move_to_end(key)
return self.stack[key]
else:
return -1
def put(self, key: int, value: int) -> None:
if key in self.stack:
self.stack.move_to_end(key)
self.stack[key] = value
elif self.size == self.capacity:
self.stack.popitem(last=False)
self.stack[key] = value
else:
self.stack[key] = value
self.size += 1
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)