Simple Python solution using OrderedDict


  • 0
    X
    from collections import OrderedDict
    
    class LRUCache(object):
    
        def __init__(self, capacity):
            """
            :type capacity: int
            """
            self.capacity = capacity
            self._cache = OrderedDict()
            
        def move(self, key, newVal=None):
            val = self._cache[key] if newVal is None else newVal
            del self._cache[key]
            self._cache[key] = val
            return val
    
        def get(self, key):
            """
            :type key: int
            :rtype: int
            """
            if key not in self._cache:
                return -1
            
            return self.move(key)
    
        def put(self, key, value):
            """
            :type key: int
            :type value: int
            :rtype: void
            """
            if key in self._cache:
                self.move(key, newVal=value)
            else:
                if len(self._cache) == self.capacity:
                    self._cache.popitem(last=False)
                self._cache[key] = value
            return None
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.