python
import sys
class Node:
def __init__(self, key, val, count=1, prev=None, next=None):
self.key = key
self.val = val
self.count = count
self.prev = prev
self.next = next
class DoubleList:
def __init__(self):
self.head = Node(0, 0, -sys.maxsize)
self.tail = Node(0, 0, sys.maxsize)
self.head.next = self.tail
self.tail.prev = self.head
self.size = 0
def add(self, node):
count = node.count
curr = self.tail
while curr.count > count:
curr = curr.prev
tail = curr.next
curr.next = node
node.prev = curr
tail.prev = node
node.next = tail
self.size += 1
def remove(self, node):
node.prev.next = node.next
node.next.prev = node.prev
node.next = None
node.prev = None
node.count += 1
self.size -= 1
return node
def removeFirst(self):
if self.head.next == self.tail:
return None
first = self.head.next
first = self.remove(first)
return first.key
class LFUCache:
def __init__(self, capacity: int):
self.cap = capacity
self.map = dict()
self.doublelist = DoubleList()
def get(self, key: int):
if key not in self.map.keys():
return -1
node = self.doublelist.remove(self.map[key])
self.doublelist.add(node)
return node.val
def put(self, key: int, value: int):
if key in self.map.keys():
node = self.doublelist.remove(self.map[key])
node.val = value
self.doublelist.add(node)
elif self.cap == self.doublelist.size:
first = self.doublelist.removeFirst()
if first == None:
return
del self.map[first]
node = Node(key, value, 1)
self.doublelist.add(node)
self.map[key] = node
else:
node = Node(key, value, 1)
self.doublelist.add(node)
self.map[key] = node
# Your LFUCache object will be instantiated and called as such:
# obj = LFUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)