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 小时前
遵守robots协议的友好爬虫
大数据·爬虫·python·算法·网络爬虫
艾斯比的日常2 小时前
Java 三色标记算法:并发垃圾回收的核心技术解析
java·开发语言·算法
CoovallyAIHub2 小时前
抛弃LLM!MIT用纯视觉方法破解ARC难题,性能接近人类水平
深度学习·算法·计算机视觉
程序猿编码2 小时前
PRINCE算法的密码生成器:原理与设计思路(C/C++代码实现)
c语言·网络·c++·算法·安全·prince
高洁012 小时前
具身智能-视觉语言导航(VLN)
深度学习·算法·aigc·transformer·知识图谱
Croa-vo2 小时前
TikTok 数据工程师三轮 VO 超详细面经:技术深挖 + 建模推导 + 压力测试全记录
javascript·数据结构·经验分享·算法·面试
蘑菇小白2 小时前
时间复杂度
数据结构·算法
czlczl200209253 小时前
算法:组合问题
算法·leetcode·职场和发展
CoderYanger3 小时前
优选算法-字符串:63.二进制求和
java·开发语言·算法·leetcode·职场和发展·1024程序员节
Cx330❀3 小时前
C++ STL set 完全指南:从基础用法到实战技巧
开发语言·数据结构·c++·算法·leetcode·面试