-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathN146 LRU.py
More file actions
48 lines (40 loc) · 1.14 KB
/
N146 LRU.py
File metadata and controls
48 lines (40 loc) · 1.14 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
class ListNode:
def __init__(self, key, val):
self.val = val
self.key = key
self.left = None
self.right = None
def __repr__(self):
return str(self.key)
class LRUCache:
def __init__(self, capacity: int):
from collections import OrderedDict
self.capacity = capacity
self.lru = OrderedDict()
self.cnt = 0
def get(self, key: int) -> int:
if key in self.lru:
self.lru.move_to_end(key)
return self.lru[key]
else:
return -1
def put(self, key: int, value: int) -> None:
if key in self.lru:
self.lru[key] = value
self.lru.move_to_end(key)
else:
self.lru[key] = value
if self.cnt < self.capacity:
self.cnt += 1
else:
del self.lru[list(self.lru.keys())[0]]
lRUCache = LRUCache(2)
lRUCache.put(1, 1)
lRUCache.put(2, 2)
print(lRUCache.get(1))
lRUCache.put(3, 3)
print(lRUCache.get(2))
lRUCache.put(4, 4)
print(lRUCache.get(1))
print(lRUCache.get(3))
print(lRUCache.get(4))