-
-
Notifications
You must be signed in to change notification settings - Fork 421
/
LRUCache.py
69 lines (54 loc) · 1.68 KB
/
LRUCache.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class ListNode(object):
def __init__(self,key,val):
self.key = key
self.value = val
self.next = None
self.prev = None
class LRUCache:
def __init__(self, capacity: int):
self.cap = capacity
self.dic = {}
self.head = ListNode(-1,-1)
self.tail = ListNode(-1,-1)
self.head.next = self.tail
self.tail.prev = self.head
def get(self, key: int) -> int:
if key in self.dic:
node = self.dic[key]
self.remove(node)
self.add(node)
return node.value
return -1
def put(self, key: int, value: int) -> None:
if key in self.dic:
node = self.dic[key]
self.remove(node)
del self.dic[node.key]
if len(self.dic)>=self.cap:
node = self.head.next
self.remove(node)
del self.dic[node.key]
node = ListNode(key,value)
self.dic[key] = node
self.add(node)
# self.show(self.head)
def remove(self,node):
prevNode = node.prev
prevNode.next = node.next
node.next.prev = prevNode
def add(self,node):
tailprev = self.tail.prev
tailprev.next = node
node.prev = tailprev
node.next = self.tail
self.tail.prev = node
# self.show(self.head)
def show(self,head):
while head:
print(head.value,end=" ")
head = head.next
print()
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)