Created
May 26, 2019 16:21
-
-
Save liruqi/a5049676b843c7cc1c60bc2c2edaa888 to your computer and use it in GitHub Desktop.
LRUCache
This file contains 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
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