-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0146-lru-cache.py
More file actions
33 lines (25 loc) · 775 Bytes
/
0146-lru-cache.py
File metadata and controls
33 lines (25 loc) · 775 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
32
33
"""
146. LRU Cache
Submitted: January 24, 2025
Runtime: 116 ms (beats 82.52%)
Memory: 78.04 MB (beats 88.47%)
"""
from collections import OrderedDict
class LRUCache(OrderedDict):
def __init__(self, capacity: int):
self.capacity = capacity
def get(self, key: int) -> int:
if key in self:
self.move_to_end(key, last=True)
return self[key]
else:
return -1
def put(self, key: int, value: int) -> None:
if key in self: self.move_to_end(key, last=True)
self[key] = value
while len(self) > self.capacity:
self.popitem(last=False)
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)