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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| class Node: def __init__(self, key, value, freq = 1): self.freq = freq
class LFUCache: def __init__(self, capacity): self.cap = capacity self.size = 0 self.min_freq = 1 self.data = dict() self.freq_table = dict()
def add_node(self, key, value, freq): node = Node(key, value, freq) self.data[key] = node if not freq in self.freq_table: self.freq_table[freq] = (node, node) return
head, rear = self.freq_table[freq] node.next = head if head is not None: head.prev = node head = node if rear is None: rear = node self.freq_table[freq] = (head, rear) def delete_node(self, key, update_min_freq_if_empty): if not key in self.data: return node = self.data[key] freq = node.freq if node.prev is not None: node.prev.next = node.next if node.next is not None: node.next.prev = node.prev
del self.data[key]
if not freq in self.freq_table: return head, rear = self.freq_table[freq] if freq in self.freq_table and node == head: head = node.next if freq in self.freq_table and node == rear: rear = node.prev if head is None or rear is None: del self.freq_table[freq] self.min_freq = update_min_freq_if_empty \ if update_min_freq_if_empty is not None and update_min_freq_if_empty == self.min_freq + 1 \ else self.min_freq else: self.freq_table[freq] = (head, rear)
def get(self, key): if not key in self.data: return None val = self.data[key].val freq = self.data[key].freq self.delete_node(key, freq + 1) self.add_node(key, val, freq + 1) return val
def put(self, key, value): if key in self.data: freq = self.data[key].freq self.delete_node(key, freq + 1) self.add_node(key, value, freq + 1) return if not key in self.data and self.size < self.cap: self.min_freq = 1 self.add_node(key, value, 1) self.size += 1 return if not self.min_freq in self.freq_table: return _, least_used_node = self.freq_table[self.min_freq] self.delete_node(least_used_node.key, None) self.min_freq = 1 self.add_node(key, value, 1)
|