Skip to content

Instantly share code, notes, and snippets.

@samedhi
Last active January 7, 2019 05:16
Show Gist options
  • Save samedhi/2f948e0853a251aa4776b7cad949c5d8 to your computer and use it in GitHub Desktop.
Save samedhi/2f948e0853a251aa4776b7cad949c5d8 to your computer and use it in GitHub Desktop.
LRU Cache (Leetcode) [Python 3]
class LRUCache:
def __init__(self, capacity):
"""
:type capacity: int
"""
assert(capacity >= 1)
self.d = {}
self.first_node = self.last_node = current_node = {}
for i in range(capacity-1):
new_node = {'next': current_node}
current_node['previous'] = new_node
current_node = self.first_node = new_node
def push(self, new_node):
new_node['next'] = self.first_node
self.first_node['previous'] = new_node
self.first_node = new_node
def remove(self, node):
if 'previous' in node and 'next' in node:
node['previous']['next'] = node['next']
node['next']['previous'] = node['previous']
elif 'previous' in node:
self.last_node = node['previous']
del self.last_node['next']
elif 'next' in node:
self.first_node = node['next']
del self.first_node['previous']
for k in ['previous', 'next']:
if k in node:
del node[k]
def get(self, key):
"""
:type key: int
:rtype: int
"""
if key in self.d:
if self.first_node is self.last_node:
return self.d[key]
node = self.d[key]
if self.first_node != node:
self.remove(node)
self.push(node)
return node['value']
else:
return -1
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: void
"""
if self.first_node is self.last_node:
self.d = {key:value}
return
if key in self.d:
self.get(key)
self.d[key]['value'] = value
else:
if 'key' in self.last_node:
del self.d[self.last_node['key']]
new_node = {'key':key, 'value':value}
self.remove(self.last_node)
self.push(new_node)
self.d[key] = new_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