Rev Leon Lonnie Love
damned mine eyes, DAMNED mine eyes!!
Here is my implementation from when I attempted this earlier this year:Tried implementing an LRU Cache on Leet Code . I understand the premise but the logic is getting me. Tried 2 approaches, but no luck. HashMap to store entries, a TreeSet to store access times, and a custom object to store key, value, and access to time together (the value of the kvp in the map). I think my misstep with this approach is storing the access times rather than combined object and overriding the get and comparison of the TreeSet.
If it's overrided to sort by access time, the first element is always the LRU. And the get, pass the key rather than the object... Idea vs implementation is a bytch.
Code:
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self._cache = OrderedDict()
def get(self, key: int) -> int:
if key in self._cache:
self._cache.move_to_end(key)
return self._cache[key]
return -1
def put(self, key: int, value: int) -> None:
if key not in self._cache:
if len(self._cache) >= self.capacity:
self._cache.popitem(last=False)
self._cache[key] = value
else:
self._cache[key] = value
self._cache.move_to_end(key)
It took 172ms to run on python. Its a pretty standard an known approach among the 3 I have come across.