Skip to content

Commit 8c2574f

Browse files
committed
LRU Cache
1 parent c05fff0 commit 8c2574f

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

146 LRU Cache.py

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
'''
2+
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
3+
4+
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
5+
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
6+
'''
7+
8+
class LRUCache(object):
9+
class Node(object):
10+
def __init__(self, key, value):
11+
self.key = key
12+
self.value = value
13+
self.prev, self.next = None, None
14+
15+
def __init__(self, capacity):
16+
"""
17+
:type capacity: int
18+
"""
19+
self.capacity, self.size = capacity, 0
20+
self.dic = {}
21+
self.head, self.tail = self.Node(-1, -1), self.Node(-1, -1)
22+
self.head.next, self.tail.prev = self.tail, self.head
23+
24+
def __remove(self, node):
25+
node.prev.next = node.next
26+
node.next.prev = node.prev
27+
node.prev, node.next = None, None
28+
29+
def __insert(self, node):
30+
node.prev, node.next = self.head, self.head.next
31+
self.head.next.prev = node
32+
self.head.next = node
33+
34+
def get(self, key):
35+
"""
36+
:rtype: int
37+
"""
38+
if key not in self.dic:
39+
return -1
40+
node = self.dic[key]
41+
self.__remove(node)
42+
self.__insert(node)
43+
return node.value
44+
45+
def set(self, key, value):
46+
"""
47+
:type key: int
48+
:type value: int
49+
:rtype: nothing
50+
"""
51+
if key in self.dic:
52+
node = self.dic[key]
53+
self.__remove(node)
54+
node.value = value
55+
self.__insert(node)
56+
else:
57+
if self.size == self.capacity:
58+
discard = self.tail.prev
59+
self.__remove(discard)
60+
del self.dic[discard.key]
61+
self.size -= 1
62+
node = self.Node(key, value)
63+
self.dic[key] = node
64+
self.__insert(node)
65+
self.size += 1
66+
67+
68+
if __name__ == "__main__":
69+
lru_cache = LRUCache(3)
70+
lru_cache.set(1, 1)
71+
lru_cache.set(2, 2)
72+
lru_cache.set(3, 3)
73+
assert lru_cache.get(0) == -1
74+
assert lru_cache.get(1) == 1
75+
lru_cache.set(1, 10)
76+
assert lru_cache.get(1) == 10
77+
lru_cache.set(4, 4)
78+
assert lru_cache.get(2) == -1

0 commit comments

Comments
 (0)