Short Python OrderedDict


  • 0
    class LRUCache(object):
        
        def __init__(self, capacity):
            self.cache = collections.OrderedDict()
            self.capacity = capacity
            
        def get(self, key):
            cache = self.cache
            if key not in cache: return -1
            val = cache.pop(key)
            cache[key] = val
            return val
    
        def put(self, key, value):
            cache = self.cache
            self.get(key)
            cache[key] = value
            if len(cache) > self.capacity:
                cache.popitem(last=False)

Log in to reply
 

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