-
Notifications
You must be signed in to change notification settings - Fork 43
/
lfu_cache.py
63 lines (58 loc) · 1.89 KB
/
lfu_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
#---------------------------------------------------------------
# LFU cache
#---------------------------------------------------------------
# V0
# https://github.com/yennanliu/CS_basics/blob/master/leetcode_python/Design/lfu_cache.py
from collections import OrderedDict
class Node:
def __init__(self, key, val, count):
self.key=key
self.val=val
self.count=count
class LFUCache:
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity=capacity
self.key_node={}
self.count_node={}
self.minV=None
def get(self, key):
"""
:type key: int
:rtype: int
"""
if not key in self.key_node: return -1
node = self.key_node[key]
del self.count_node[node.count][key]
if not self.count_node[node.count]:
del self.count_node[node.count]
node.count+=1
if not node.count in self.count_node:
self.count_node[node.count]=OrderedDict()
self.count_node[node.count][key]=node
if not self.minV in self.count_node:
self.minV+=1
return node.val
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: void
"""
# if element exists, -> update value and count + 1
if self.capacity==0: return None
if key in self.key_node:
self.key_node[key].val=value
self.get(key)
else:
if len(self.key_node) == self.capacity:
item=self.count_node[self.minV].popitem(last=False)
del self.key_node[item[0]]
node=Node(key,value,1)
self.key_node[key]=node
if not 1 in self.count_node:
self.count_node[1]=OrderedDict()
self.count_node[1][key]=node
self.minV=1