Python Implementation (using auxiliar stack/dictionary)


  • 0
    R
    class LRUCache(object):
        def __init__(self, capacity):
            self.max_capacity = capacity
            self.cache = {}
            self.cache_key = []
    
        def get(self, key):
            if(key in self.cache):
                del self.cache_key[self.cache_key.index(key)]
                self.cache_key.append(key)
                return (self.cache[key])
            else:
                return -1
    
    
        def put(self, key, value):
            if(key in self.cache):
                print("evicts " + str(self.cache_key[self.cache_key.index(key)]))
                del self.cache_key[self.cache_key.index(key)]
            elif(len(self.cache) == self.max_capacity):
                del self.cache[self.cache_key[0]]
                del self.cache_key[0]
            self.cache[key] = value
            self.cache_key.append(key)
    

Log in to reply
 

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