146. LRU Cache

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:getandput.

get(key)- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value)- Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

Follow up:
Could you do both operations inO(1)time complexity?

Method 1 Old school Hashmap + LinkedList

class Node():
    def __init__(self, key, val):
        self.key = key
        self.val = val
        self.next = None
        self.prev = None

class LRUCache(object):

    def __init__(self, capacity):
        """
        :type capacity: int
        """
        self.hm = {}
        self.capacity = capacity
        self.head = Node(None, None)
        self.tail = Node(None, None)
        self.head.next = self.tail
        self.tail.prev = self.head

    def get(self, key):
        """
        :type key: int
        :rtype: int
        """
        if key in self.hm:
            node = self.hm[key]
            self.extract_node(node)
            self.move_to_head(node)
            return node.val

        return -1

    def put(self, key, value):
        """
        :type key: int
        :type value: int
        :rtype: void
        """
        if key in self.hm:
            node = self.hm[key]
            node.val = value
            self.extract_node(node)
        else:
            node = Node(key, value)
            if len(self.hm) == self.capacity:
                last = self.tail.prev
                del self.hm[last.key]
                last.prev.next = self.tail
                self.tail.prev = last.prev
            self.hm[key] = node
        self.move_to_head(node)

    def extract_node(self, node):
        node.prev.next = node.next
        node.next.prev = node.prev

    def move_to_head(self, node):
        node.next = self.head.next
        node.prev = self.head

        self.head.next.prev = node
        self.head.next = node

results matching ""

    No results matching ""