-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp146.py
More file actions
111 lines (84 loc) · 2.56 KB
/
p146.py
File metadata and controls
111 lines (84 loc) · 2.56 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
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# https://leetcode.com/problems/lru-cache/
from typing import Dict
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.data = []
def get(self, key: int) -> int:
if not self.data:
return -1
i = 0
while i < len(self.data):
if self.data[i][0] == key:
break
i += 1
if i == len(self.data):
return -1
item = self.data.pop(i)
self.data.insert(0, item)
return self.data[0][1]
def put(self, key: int, value: int) -> None:
idx = self.get(key)
if idx == -1:
self.data.insert(0, [key, value])
if len(self.data) > self.capacity:
self.data.pop()
else:
self.data[0][1] = value
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
class Node:
def __init__(self, key: int, val: int, prev: 'Node' = None, next: 'Node' = None) -> None:
self.key = key
self.val = val
self.prev = prev
self.next = next
class LRUCacheV2:
def __init__(self, capacity: int):
self.capacity = capacity
self.keys : Dict[int, Node] = {}
self.head: Node = None
self.last: Node = None
def _add(self, node: Node):
node.prev = None
node.next = self.head
if self.head:
self.head.prev = node
self.head = node
if self.last is None:
self.last = node
self.last.next = None
def _remove(self, node: Node):
if self.head == node:
self.head = node.next
node.next = None
return
if self.last == node:
self.last = node.prev
if self.last:
self.last.next = None
return
node.prev.next = node.next
node.next.prev = node.prev
def get(self, key: int) -> int:
if key not in self.keys:
return -1
node = self.keys.get(key)
self._remove(node)
self._add(node)
return node.val
def put(self, key: int, value: int) -> None:
if key in self.keys:
node = self.keys[key]
node.val = value
self._remove(node)
self._add(node)
return
node = Node(key, value)
self.keys[key] = node
self._add(node)
if len(self.keys) > self.capacity:
del self.keys[self.last.key]
self._remove(self.last)