力扣刷题Day 37:LRU 缓存(146)

1.题目描述

2.思路

方法1:直接用Python封装好的数据结构OrderedDict(兼具哈希表与双向链表的数据结构)。

方法2:哈希表辅以双向链表。

3.代码(Python3)

方法1:

复制代码
class LRUCache(collections.OrderedDict):

    def __init__(self, capacity: int):
        super().__init__()
        self.capacity = capacity

    def get(self, key: int) -> int:
        if key not in self:
            return -1
        self.move_to_end(key)
        return self[key]

    def put(self, key: int, value: int) -> None:
        if key in self:
            self.move_to_end(key)
        self[key] = value
        if len(self) > self.capacity:
            self.popitem(last=False)

方法2:

复制代码
class DLinkedNode:
    def __init__(self, key=0, value=0):
        self.key = key
        self.value = value
        self.prev = None
        self.next = None


class LRUCache:

    def __init__(self, capacity: int):
        self.cache = dict()
        # 伪头和伪尾
        self.head = DLinkedNode()
        self.tail = DLinkedNode()
        self.head.next = self.tail
        self.tail.prev = self.head
        self.capacity = capacity
        self.size = 0

    def get(self, key: int) -> int:
        if key not in self.cache:
            return -1
        node = self.cache[key]
        self.move_to_head(node)
        return node.value

    def put(self, key: int, value: int) -> None:
        print(self.size, self.capacity)
        if key not in self.cache:
            node = DLinkedNode(key, value)
            self.cache[key] = node
            self.add_to_head(node)
            self.size += 1
            if self.size > self.capacity:
                removed = self.remove_tail()
                self.cache.pop(removed.key)
                self.size -= 1
        else:
            node = self.cache[key]
            node.value = value
            self.move_to_head(node)
        
    def add_to_head(self, node):
        node.prev = self.head
        node.next = self.head.next
        self.head.next.prev = node
        self.head.next = node
        
    def remove_node(self, node):
        node.prev.next = node.next
        node.next.prev = node.prev
    
    def move_to_head(self, node):
        self.remove_node(node)
        self.add_to_head(node)
    
    def remove_tail(self):
        node = self.tail.prev
        self.remove_node(node)
        return node

4.执行情况

方法1:

方法2:

5.感想

这两个方法都是官方题解给的,我第一次接触这种LRU的题,没能想出来解决办法。

相关推荐
小魏每天都学习7 分钟前
【算法——c/c++]
c语言·c++·算法
智码未来学堂41 分钟前
探秘 C 语言算法之枚举:解锁解题新思路
c语言·数据结构·算法
Halo_tjn1 小时前
基于封装的专项 知识点
java·前端·python·算法
春日见1 小时前
如何避免代码冲突,拉取分支
linux·人工智能·算法·机器学习·自动驾驶
副露のmagic1 小时前
更弱智的算法学习 day59
算法
u0109272712 小时前
C++中的RAII技术深入
开发语言·c++·算法
2401_832131953 小时前
模板错误消息优化
开发语言·c++·算法
金枪不摆鳍3 小时前
算法--二叉搜索树
数据结构·c++·算法
近津薪荼3 小时前
优选算法——双指针6(单调性)
c++·学习·算法
helloworldandy4 小时前
高性能图像处理库
开发语言·c++·算法