LRU Cache
Solution:
class DoublelyLinkedList:
def __init__(self, key, value):
self.key = key
self.value = value
self.prev = self.next = None #made mistake to put as parameters
class LRUCache:
# @param capacity, an integer
def __init__(self, capacity):
self.capacity = capacity
self.hashmap = {}
# double dummy head and tail pointer
self.head = DoublelyLinkedList(-1, -1)
self.tail = DoublelyLinkedList(-1, -1)
self.tail.prev = self.head
self.head.next = self.tail
# @return an integer
def get(self, key):
# write your code here
if key not in self.hashmap:
return -1
#remove the exsiting node and take advantage from dobuledLinkedList
current = self.hashmap[key]
current.prev.next = current.next
current.next.prev = current.prev
#add the current node to the tail
self.addNodeToTail(current)
# return value
return self.hashmap[key].value
# @param key, an integer
# @param value, an integer
# @return nothing
def set(self, key, value):
# write your code here
# check if the key exist before insert
if self.get(key) != -1:
self.hashmap[key].value = value
return
if len(self.hashmap) >= self.capacity:
self.hashmap.pop(self.head.next.key) # forget pop node from hashmap
# the first node is dummy, we will remove the second
self.head.next = self.head.next.next
self.head.next.prev = self.head # delete next node.
inserNode = DoublelyLinkedList(key, value)
self.hashmap[key] = inserNode
self.addNodeToTail(inserNode)
def addNodeToTail(self, current):
current.prev = self.tail.prev
self.tail.prev = current
current.prev.next = current
current.next = self.tailLast updated