forked from y-ncao/Python-Study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLRU_Cache.py
67 lines (58 loc) · 2.21 KB
/
LRU_Cache.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
"""
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
"""
class LRUCache:
# @param capacity, an integer
def __init__(self, capacity):
self.capacity = capacity
self.cache = collections.OrderedDict()
# @return an integer
def get(self, key):
if key in self.cache:
value = self.cache[key]
del self.cache[key]
self.cache[key] = value
return value
return -1
# @param key, an integer
# @param value, an integer
# @return nothing
def set(self, key, value):
if key not in self.cache and len(self.cache) >= self.capacity:
self.cache.popitem(last=False)
elif key in self.cache:
del self.cache[key]
self.cache[key] = value
# Keep a note here, always delete the item. Cause update the key won't update the order
"""
# @param capacity, an integer
def __init__(self, capacity):
self.capacity = capacity
self.cache = {}
self.queue = []
# @return an integer
def get(self, key):
if key in self.cache:
self.queue.remove(key)
self.queue.append(key)
return self.cache[key]
return -1
# @param key, an integer
# @param value, an integer
# @return nothing
def set(self, key, value):
if key in self.cache:
self.queue.remove(key)
elif len(self.cache) >= self.capacity:
remove = self.queue.pop(0)
self.cache.pop(remove)
self.queue.append(key)
self.cache[key] = value
"""
# Checked online, so changed to use python's ordered dictionary
# So obsoleted queue
# Also, there was some understanding mistake
# When get a key, it won't delete the key, but just reorder it to highier rank
# Just like a cache. Don't think it as a dict