Skip to content

Instantly share code, notes, and snippets.

@liruqi
Created May 26, 2019 16:21
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 liruqi/a5049676b843c7cc1c60bc2c2edaa888 to your computer and use it in GitHub Desktop.
Save liruqi/a5049676b843c7cc1c60bc2c2edaa888 to your computer and use it in GitHub Desktop.
LRUCache
class LRUCache(collections.OrderedDict):
def __init__(self, capacity: int):
self.maxsize = capacity
def get(self, key: int) -> int:
if key in self:
value = super().__getitem__(key)
self.move_to_end(key)
return value
return -1
def put(self, key: int, value: int) -> None:
if key in self:
if len(self) >= self.maxsize:
oldest = next(iter(self))
del self[oldest]
else:
self.move_to_end(key)
super().__setitem__(key, value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment