Python 2 dicts and time


  • 0
    import time
    
    class LRUCache(object):
    
        def __init__(self, capacity):
            """
            :type capacity: int
            """
            self.cache = {}
            self.used_at = {}
            self.capacity = capacity 
    
        def get(self, key):
            """
            :rtype: int
            """
            item = self.cache.get(key, -1)
            if item != -1:
                self.used_at[key] = time.time()
    
            return item
    
        def set(self, key, value):
            """
            :type key: int
            :type value: int
            :rtype: nothing
            """
            if key not in self.cache and len(self.cache) == self.capacity:
                self._invalidate_lru()
            
            self.cache[key] = value
            self.used_at[key] = time.time()
                
        def _invalidate_lru(self):
            invalid_key = min(self.used_at, key=self.used_at.get)
            self.cache.pop(invalid_key, None)
            self.used_at.pop(invalid_key, None)
    

    However it's better to use OrderedDict(implement later).
    :levitate:


Log in to reply
 

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