146. LRU Cache (Medium) - TengnanYao/daily_leetcode GitHub Wiki

class LRUCache(object):

    def __init__(self, capacity):
        """
        :type capacity: int
        """
        self.h = collections.OrderedDict()
        self.n = capacity

    def get(self, key):
        """
        :type key: int
        :rtype: int
        """
        if self.h.get(key) == None:
            return -1
        self.h[key] = self.h.pop(key)
        return self.h[key]

    def put(self, key, value):
        """
        :type key: int
        :type value: int
        :rtype: None
        """
        if self.h.get(key) == None:
            if len(self.h) >= self.n:
                self.h.popitem(last = False)
        else:
            del self.h[key]
        self.h[key] = value


# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)