Created
September 17, 2019 11:09
-
-
Save alphaCoder/744b2743e685f36b7a87654648842bed to your computer and use it in GitHub Desktop.
LRU Cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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