-
Notifications
You must be signed in to change notification settings - Fork 0
/
146. LRU Cache.py
91 lines (80 loc) · 2.12 KB
/
146. 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
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
class Node:
def __init__(self, k, v):
self.key = k
self.val = v
self.prev = None
self.next = None
h
class LRUCache:
#Tail is the most accessed node. Head is need to be deleted while capacity is full in putting process..
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
self.dic = dict()
self.head = Node(0, 0)
self.tail = Node(0, 0)
self.head.next = self.tail
self.tail.prev = self.head
def get(self, key):
"""
:type key: int
:rtype: int
"""
if key in self.dic:
n = self.dic[key]
self._remove(n)
self._add(n)
return n.val
return -1
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: None
"""
if key in self.dic:
self._remove(self.dic[key])
n = Node(key, value)
self._add(n)
self.dic[key] = n
if len(self.dic) > self.capacity:
n = self.head.next
self._remove(n)
del self.dic[n.key]
def _remove(self, node):
p = node.prev
n = node.next
p.next = n
n.prev = p
def _add(self, node):
p = self.tail.prev
p.next = node
self.tail.prev = node
node.prev = p
node.next = self.tail
obj = LRUCache(2)
obj.put(1,1)
obj.put(2,2)
obj.put(3,3)
print obj.get(2)
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
from collections import OrderedDict
class LRUCache:
def __init__(self, Capacity):
self.size = Capacity
self.cache = OrderedDict()
def get(self, key):
if key not in self.cache: return -1
val = self.cache[key]
self.cache.move_to_end(key)
return val
def put(self, key, val):
if key in self.cache: del self.cache[key]
self.cache[key] = val
if len(self.cache) > self.size:
self.cache.popitem(last=False)