LeetCode 146. LRU Cache 时间复杂度(O(1))

时间复杂度(O(1)), 思想:使用hash存储数据和数据信息

class DNode:
    def __init__(self, data, pre, next):
        self.data = data
        self.pre = pre
        self.next = next


class LRUCache:

    def __init__(self, capacity: int):

        self.capacity = capacity
        self.hash_map = {}
        self.node_head = DNode(None, None, None)
        self.node_tail = DNode(None, None, None)
        self.node_head.next, self.node_tail.pre = self.node_tail, self.node_head

    def update_node_list(self, key_node, in_list):
        if in_list: key_node.next.pre, key_node.pre.next = key_node.pre, key_node.next

        key_node.pre, key_node.next = self.node_tail.pre, self.node_tail
        self.node_tail.pre.next = key_node
        self.node_tail.pre = key_node

    def get(self, key: int) -> int:
        if key in self.hash_map:
            key_node = self.hash_map[key][1]
            self.update_node_list(key_node, 1)
            return self.hash_map[key][0]
        return -1

    def put(self, key: int, value: int) -> None:

        if key not in self.hash_map:
            key_node = DNode(key, None, None)
            self.hash_map[key] = (value, key_node)
            self.update_node_list(key_node, False)
            if len(self.hash_map) > self.capacity:
                remove_node = self.node_head.next
                self.node_head.next.next.pre = self.node_head
                self.node_head.next = self.node_head.next.next
                self.hash_map.pop(remove_node.data)
        else:
            key_node = self.hash_map[key][1]
            self.hash_map[key] = (value, key_node)
            self.update_node_list(key_node, True)

 

你可能感兴趣的:(LeetCode)