Leetcode 146. LRU 缓存

注意的点:

1、这道题本质是要求一个可以排序的字典(因为O(1)的时间复杂度就是字典),所以要不就用collections自带的OrderDict,要不然就用字典加双头链表自己实现一个。

2、OrderedDict的两个方法:

.move_to_end(key, last=False):把元素后移一位,last=True的话就是移动到最后

.popitem(last=True):把最后位置的元素pop出去

解法一:python的OrderDict

python 复制代码
from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.cache = OrderedDict()

    def get(self, key: int) -> int:
        if key in self.cache:
            self.cache.move_to_end(key, last=False)
            return self.cache[key]
        else:
            return -1

    def put(self, key: int, value: int) -> None:
        self.cache[key] = value
        self.cache.move_to_end(key, last=False)
        if len(self.cache) > self.capacity:
            self.cache.popitem(last=True)
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)

解法二:字典加双链表

python 复制代码
class LRUCache:

    def __init__(self, capacity: int):
    
        self.max = capacity
        self.store = dict()  
        self.head = Linknode(None, None)
        self.tail = self.head

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

    def put(self, key: int, value: int) -> None:
        if key not in self.store.keys():
            node = Linknode(None, key)
            self.tail.next = node
            # self.tail = self.tail.next
            self.tail = node
            if len(self.store.keys()) == self.max:
                tempnode = self.head.next
                removed_key = tempnode.val
                self.head.next = tempnode.next
                tempnode.next = None
                self.store.pop(removed_key)
            self.store[key] = value
        else:  # 找到这个
            self.addcurrentnode2tail(key)
            self.store[key] = value
    
    def addcurrentnode2tail(self, akey):
        print(889, self.head)
        hi = self.head
        while hi.next:
            if hi.next.val == akey:
                break
            hi = hi.next
        # 把hi移动到链表的尾部(可能已经是末尾了)
        if hi.next.next:
            temp = hi.next.next
            hi.next.next = None
            self.tail.next = hi.next
            hi.next = temp
            self.tail = self.tail.next
      
class Linknode:
    def __init__(self, ne=None, val=None):
        self.next = ne
        self.val = val
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
相关推荐
工具派1 分钟前
视频场景检测是怎么找到切镜头位置的?三种思路与实测
算法·计算机视觉·视频
钓鱼的肝5 分钟前
csp-j-s总结(1)
c++·笔记·算法·青少年编程
流云枫6 分钟前
001-Transformer架构与Self-Attention机制深度解析
算法
生信大杂烩27 分钟前
Xenium H&E空间原位可视化——细胞轮廓、基因表达与转录本可视化
python·算法·数据分析
linx29538 分钟前
第七章 · 标准库容器、算法与 ranges
c语言·开发语言·数据结构·c++·算法
钓鱼的肝43 分钟前
csp-j-s总结(4)
c++·经验分享·笔记·算法
橘子汽水1681 小时前
Leetcode 763,45 划分字母区间 跳跃游戏II
数据结构·算法·leetcode
天天喝旺仔2 小时前
Git 内部原理深度解析:从 blob/tree/commit 对象到 packfile 与垃圾回收
数据结构·数据库·git·算法·哈希
AIGCmagic社区2 小时前
KITTI AbsRel从6.5压到5.4,Marigold V2用一张32GB卡把编辑DiT收成单步深度估计
人工智能·算法·aigc·ai多模态
青少儿编程课堂2 小时前
多源最短路与最小环(Floyd 算法图论解析)
c++·python·算法·bfs·信息学竞赛