-
Notifications
You must be signed in to change notification settings - Fork 0
/
LRU Cache (Using Arrays)
59 lines (51 loc) · 1.57 KB
/
LRU Cache (Using Arrays)
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
class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.lrucache = {}
self.lrucount = []
self.cap = capacity
def get(self, key):
"""
:type key: int
:rtype: int
"""
if key in self.lrucache:
if key in self.lrucount:
self.lrucount.remove(key)
self.lrucount.append(key)
return self.lrucache[key]
else:
return -1
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: None
"""
# print(self.lrucache)
# print(self.lrucount)
if key in self.lrucache:
if key in self.lrucount:
self.lrucount.remove(key)
self.lrucount.append(key)
self.lrucache[key] = value
elif len(self.lrucache)<self.cap:
self.lrucache[key] = value
if key in self.lrucount:
self.lrucount.remove(key)
self.lrucount.append(key)
else:
self.lrucache.pop(self.lrucount.pop(0))
# self.lrucount.pop(min(self.lrucount, key=self.lrucount.get))
self.lrucache[key] = value
if key in self.lrucount:
self.lrucount.remove(key)
self.lrucount.append(key)
# print(self.lrucache)
# print(self.lrucount)
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)