-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLRUCache.py
40 lines (36 loc) · 1003 Bytes
/
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
import collections
class LRUCache:
# @param capacity, an integer
def __init__(self, capacity):
LRUCache.capacity = capacity
LRUCache.Dict = collections.OrderedDict()
LRUCache.numItems = 0
# @return an integer
def get(self, key):
try:
val = LRUCache.Dict[key]
del LRUCache.Dict[key]
LRUCache.Dict[key] = val
return val
except:
return -1
# @param key, an integer
# @param value, an integer
# @return nothing
def set(self, key, value):
try:
del LRUCache.Dict[key]
LRUCache.Dict[key] = value
return
except:
if LRUCache.numItems == LRUCache.capacity:
LRUCache.Dict.popitem(last = False)
LRUCache.numItems -= 1
LRUCache.Dict[key] = value
LRUCache.numItems +=1
return
s = LRUCache(2)
s.set(2,8)
s.set(3,2)
s.set(4,9)
print s.get(2)