-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy path146.py
73 lines (61 loc) · 2.07 KB
/
146.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
__________________________________________________________________________________________________
sample 184 ms submission
class LRUCache:
def __init__(self, capacity: int):
self.cache = {}
self.capacity = capacity
self.n = 0
def get(self, key: int) -> int:
if key in self.cache:
val = self.cache[key]
del self.cache[key]
self.cache[key] = val
return val
else:
return -1
def put(self, key: int, value: int) -> None:
if key in self.cache:
del self.cache[key]
self.cache[key] = value
else:
if self.n < self.capacity:
self.cache[key] = value
self.n += 1
else:
for k in self.cache:
del self.cache[k]
break
self.cache[key] = value
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
__________________________________________________________________________________________________
sample 21384 kb submission
class LRUCache:
def __init__(self, capacity: int):
self.dic = {}
#self.dic = collections.OrderedDict()
self.remain = capacity
def get(self, key: int) -> int:
if key not in self.dic:
return -1
v = self.dic.pop(key)
self.dic[key]=v
return v
def put(self, key: int, value: int) -> None:
if key in self.dic:
self.dic.pop(key)
else:
if self.remain>0:
self.remain-=1
else:
List = list(self.dic)
self.dic.pop(List[0])
self.dic[key]=value
#print(self.dic)
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
__________________________________________________________________________________________________