Intuitive Pythonic solution using OrderedDict

  • 0

    I found many of the Python solutions for this problem to be almost unreadable. This is my version that overrides python's ordereddict that is much shorter and easier to understand

    class LRUCache(collections.OrderedDict):
        # @param capacity, an integer
        def __init__(self, capacity):
            self.capacity = capacity
            super(LRUCache, self).__init__()
        # @return an integer
        def get(self, key):
            if key in self:
                self[key] = self[key]
                return self[key]
            return -1
        # @param key, an integer
        # @param value, an integer
        # @return nothing
        def set(self, key, value):
            self[key] = value
            if len(self) > self.capacity:
        def __setitem__(self, key, value):
            if key in self:
                del self[key]
            collections.OrderedDict.__setitem__(self, key, value)

  • 0

    Excellent solution, although didn't improve timing, but more readable.

  • 0

    well, i think it does improve timing, but instead it increase the spacing, as OrderDict is using a double linked list to keep track.

Log in to reply

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