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)
相关推荐
得物技术17 小时前
得物推荐系统诊断 Agent:从 “调接口” 到 “会思考”|AICon 演讲整理
人工智能·算法·架构
Lugas18 小时前
为啥说男生找对象尽量在25岁前找到?
算法
MrZhao40018 小时前
从能跑到可用:一个 Agent Harness 还差哪些工程闭环?
算法
小杍随笔18 小时前
【 .npmrc 终极配置指南:统一管理 npm/pnpm 缓存与全局目录,告别磁盘混乱】
前端·缓存·npm
IvorySQL18 小时前
PG 日报|新增 VFD 缓存监控视图,精细化数据库调优
大数据·数据库·人工智能·缓存·postgresql·区块链
QN1幻化引擎18 小时前
Gravity-Anchored Cognitive Field Architecture: The DalinX V8/V10 Implementation
java·前端·算法
学计算机的计算基19 小时前
LeetCode 图论四题精讲:BFS、拓扑排序、Trie 树的模板与优化
java·笔记·算法
浩瀚地学19 小时前
【面试算法笔记】0202-链表-基本功能实现
java·经验分享·笔记·算法·面试
tkevinjd19 小时前
416分割等和子集
java·python·算法·leetcode·职场和发展
Keven_1119 小时前
算法札记:Tarjan与拓扑序(Topo)的关系
算法·拓扑·tarjan