Skip to content

Instantly share code, notes, and snippets.

@alphaCoder
Created September 17, 2019 11:09
Show Gist options
  • Save alphaCoder/744b2743e685f36b7a87654648842bed to your computer and use it in GitHub Desktop.
Save alphaCoder/744b2743e685f36b7a87654648842bed to your computer and use it in GitHub Desktop.
LRU Cache
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.cache = OrderedDict()
def get(self, key: int) -> int:
val = -1
if key in self.cache:
val = self.cache[key]
del self.cache[key]
self.cache[key] = val
return val
def put(self, key: int, value: int) -> None:
if key in self.cache:
del self.cache[key]
elif self.capacity == len(self.cache):
oldest = next(iter(self.cache))
del self.cache[oldest]
self.cache[key] = value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment