-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0146.py
More file actions
35 lines (24 loc) · 894 Bytes
/
0146.py
File metadata and controls
35 lines (24 loc) · 894 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
34
35
from collections import deque
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.history = deque([], capacity)
self.map = {}
def get(self, key: int) -> int:
result = self.map.get(key, None)
if result == None:
return -1
if key in self.history:
self.history.remove(key)
self.history.append(key)
return result
def put(self, key: int, value: int) -> None:
if key in self.history:
self.history.remove(key)
if len(self.history) == self.capacity:
remove_key = self.history.popleft()
del self.map[remove_key]
self.map[key] = value
if key in self.history:
self.history.remove(key)
self.history.append(key)