-
Notifications
You must be signed in to change notification settings - Fork 1
/
lru_cache.py
36 lines (28 loc) · 871 Bytes
/
lru_cache.py
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
34
35
36
# https://leetcode.com/problems/lru-cache/
from collections import deque
class LRUCache:
def __init__(self, capacity: int):
self.c = capacity
self.m = dict()
self.deq = deque()
def get(self, key: int) -> int:
if key in self.m:
value = self.m[key]
self.deq.remove(key)
self.deq.append(key)
return value
else:
return -1
def put(self, key: int, value: int) -> None:
if not key in self.m:
if len(self.m) == self.c:
oldest = self.deq.popleft()
del self.m[oldest]
else:
self.deq.remove(key)
self.m[key] = value
self.deq.append(key)
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)