目录

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)
本文是转载文章,点击查看原文
如有侵权,请联系 xyy@jishuzhan.net 删除
相关推荐
天天扭码16 分钟前
偶遇天才算法题 | 拼劲全力,无法战胜 😓
前端·算法·面试
_Djhhh22 分钟前
【Redis】缓存三剑客问题实践(上)
数据库·redis·缓存
2401_8786247931 分钟前
opencv(双线性插值原理)
人工智能·算法·计算机视觉
小豪GO!33 分钟前
数据结构-八大排序
数据结构·算法·排序算法
烟锁池塘柳033 分钟前
【数学建模】随机森林算法详解:原理、优缺点及应用
算法·随机森林·数学建模
极昆仑智慧1 小时前
多模态知识图谱:重构大模型RAG效能新边界
人工智能·算法·语言模型·自然语言处理·知识图谱
天天扭码1 小时前
面试官:算法题”除自身以外数组的乘积“ 我:😄 面试官:不能用除法 我:😓
前端·算法·面试
龙萌酱2 小时前
力扣每日打卡17 49. 字母异位词分组 (中等)
前端·javascript·算法·leetcode
好易学数据结构2 小时前
可视化图解算法:按之字形顺序打印二叉树( Z字形、锯齿形遍历)
数据结构·算法·leetcode·面试·二叉树·力扣·笔试·遍历·二叉树遍历·牛客网·层序遍历·z·z字形遍历·锯齿形遍历
慕容青峰2 小时前
【第十六届 蓝桥杯 省 C/Python A/Java C 登山】题解
c语言·c++·python·算法·蓝桥杯·sublime text