Skip to content

Instantly share code, notes, and snippets.

@vancexu
Created March 10, 2021 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vancexu/0190aae80f4aec2b2156724fef9655e1 to your computer and use it in GitHub Desktop.
Save vancexu/0190aae80f4aec2b2156724fef9655e1 to your computer and use it in GitHub Desktop.
class Node:
def __init__(self, key=-1, val=-1, prev=None, next=None):
self.key = key
self.val = val
self.prev = prev
self.next = next
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.dic = {}
self.dummy = Node()
self.tail = self.dummy
def toTail(self, key):
node = self.dic[key]
if node == self.tail:
return
prev = node.prev
next = node.next
prev.next = next
if next:
next.prev = prev
node.prev = self.tail
node.next = None
self.tail.next = node
self.tail = node
def removeHead(self):
head = self.dummy.next
if not head:
return
if head == self.tail:
self.tail = self.dummy
del self.dic[head.key]
prev = self.dummy
next = head.next
prev.next = next
if next:
next.prev = prev
head.next = None
head.prev = None
def get(self, key: int) -> int:
if key not in self.dic:
return -1
self.toTail(key)
return self.dic[key].val
def put(self, key: int, value: int) -> None:
if key in self.dic:
self.dic[key].val = value
self.toTail(key)
return
if len(self.dic) == self.capacity:
self.removeHead()
node = Node(key, value)
self.dic[key] = node
self.tail.next = node
node.prev = self.tail
self.tail = node
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment