LRU/LFU
146. LRU Cache
Design a cache includes 2 functions get(key) - Get the value of the key if the key exists in the cache, otherwise return -1. put(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.
getandputare O(1) operationsUse doubleLinkedList and HashMap
A removeNode and addToHead function
A head and tail Node, the recent update note is next to head
class Node:
def __init__(self, key=0, val=0):
self.key = key
self.val = val
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity: int):
self.hash = {}
self.count = 0
self.capacity = capacity
self.head, self.tail = Node(), Node()
self.head.next = self.tail
self.tail.prev = self.head
def moveToHead(self, node):
node.next = self.head.next
node.next.prev = node
self.head.next = node
node.prev= self.head
def removeNode(self, node):
node.next.prev = node.prev
node.prev.next = node.next
def get(self, key: int) -> int:
if key not in self.hash: return -1
node = self.hash[key]
self.removeNode(node)
self.moveToHead(node)
return node.val
def put(self, key: int, value: int) -> None:
if key in self.hash:
node = self.hash[key]
node.val = value
self.removeNode(node)
self.moveToHead(node)
else:
node = Node(key, value)
self.hash[key] = node
self.moveToHead(node)
self.count +=1
if self.count > self.capacity:
self.hash.pop(self.tail.prev.key)
self.removeNode(self.tail.prev)
self.count -= 1460. LFU Cache
Design a data structure supports 2 functions get(key) - Get the value of the key if the key exists in the cache, otherwise return -1. put(key, value) - Set or insert the value if the key is not already present. When the cache reaches its capacity, it should invalidate the least frequently used item before inserting a new item. For the purpose of this problem, when there is a tie (i.e., two or more keys that have the same frequency), the least recently used key would be evicted
getandputare O(1) operations3 hashMap
values
counts
countToKey>
Use DoubleLinkedList and 2 HashMap (see description)
NodeMap<key, Node>
FreqMap<freq, doublelLinkedList>
Last updated
Was this helpful?