-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path146_LRUCache.py
52 lines (39 loc) · 1.41 KB
/
146_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
# 146. LRU Cache
# Neetcode's solution
# Doubly Linked List, Hashmap.
class Node:
def __init__(self, key, val):
self.key, self.val = key, val
self.prev = self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.capacity = abs(capacity)
self.cache = {}
self.left, self.right = Node(0,0), Node(0,0)
self.left.next, self.right.prev = self.right, self.left
def remove(self, node):
prev, next_ = node.prev, node.next
prev.next, next_.prev = next_, prev
def insert(self, node):
prev, next_ = self.right.prev, self.right
prev.next = next_.prev = node
node.next, node.prev = next_, prev
def get(self, key: int) -> int:
if key in self.cache:
self.remove(self.cache[key])
self.insert(self.cache[key])
return self.cache[key].val
return -1
def put(self, key: int, value: int) -> None:
if key in self.cache:
self.remove(self.cache[key])
self.cache[key] = Node(key, value)
self.insert(self.cache[key])
if len(self.cache)>self.capacity:
lru = self.left.next
self.remove(lru)
del self.cache[lru.key]
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)