leetcode 146:LRU缓存

题目描述:
请你设计并实现一个满足 LRU (最近最少使用) 缓存 约束的数据结构。
实现 LRUCache 类:

  1. LRUCache(int capacity) 以 正整数 作为容量 capacity 初始化 LRU 缓存
  2. int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
  3. void put(int key, int value) 如果关键字 key 已经存在,则变更其数据值 value ;如果不存在,则向缓存中插入该组 key-value 。如果插入操作导致关键字数量超过 capacity ,则应该 逐出 最久未使用的关键字。
    函数 get 和 put 必须以 O(1) 的平均时间复杂度运行。
    示例:
    输入
    [“LRUCache”, “put”, “put”, “get”, “put”, “get”, “put”, “get”, “get”, “get”]
    [[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
    输出
    [null, null, null, 1, null, -1, null, -1, 3, 4]

解释
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // 缓存是 {1=1}
lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
lRUCache.get(1); // 返回 1
lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}
lRUCache.get(2); // 返回 -1 (未找到)
lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}
lRUCache.get(1); // 返回 -1 (未找到)
lRUCache.get(3); // 返回 3
lRUCache.get(4); // 返回 4
思路:
按照LRU算法的方式进行模拟。

  1. 使用python库import collections中自带的有序字典库进行实现,但是在面试中一般不能直接使用这个方式完成代码,因为面试想要考核的是双星链表。
    代码:
import collections
# 本题使用python自带的字典无法实现按照元素的插入顺序排列

class LRUCache(object):

    def __init__(self, capacity):
        """
        :type capacity: int
        """
        self.capacity = capacity
        self.dict = collections.OrderedDict()
        self.use = 0

    def get(self, key):
        """
        :type key: int
        :rtype: int
        """
        if key in self.dict:  # 字典的get函数的时间复杂度是O(n),存在返回value不存在返回NONE
            a = self.dict.pop(key)
            self.dict[key] = a
            return a
        else:
            return -1

    def put(self, key, value):
        """
        :type key: int
        :type value: int
        :rtype: None
        """
        if key in self.dict:
            self.dict.pop(key)
            self.dict[key] = value
        else:
            self.dict[key] = value
            self.use += 1
            if self.use > self.capacity:
                self.dict.popitem(last=False)
                # 这里last为true从后面删除最后一个,为false删除第一个,第一个在这里就是插入最久的一个
  1. 使用dict+双向链表实现
    dict: <key, node>这里dict直接放node方便对双向链表直接进行操作,保证时间复杂度为O(1)。 双向链表是用来维护缓存放入的内容,如get一次就从链表中拿到链表的最前端,put一次看是否需要删除一个结点,如需删除就删除双向链表最后一个结点,然后把新加入的放到链表的最前端。
class Node(object):
    def __init__(self, key= 0, value = 0):
        self.key = key
        self.value = value
        self.pre = None
        self.next = None


class LRUCache(object):

    def __init__(self, capacity):
        """
        :type capacity: int
        """
        self.capacity = capacity
        self.use = 0
        self.dict = dict()
        # 用两个哨兵结点,来帮助双向链表的转换,进而避免每次插入删除时检测是否为头尾的情况
        self.head = Node()
        self.tail = Node()
        self.head.next = self.tail
        self.tail.pre = self.head

    def get(self, key):
        """
        :type key: int
        :rtype: int
        """

        if key in self.dict:
            node = self.dict[key]
            self.remove_node(node)
            self.addTohead(node)
            return node.value
        else:
            return -1

    def put(self, key, value):
        """
        :type key: int
        :type value: int
        :rtype: None
        """
        if key in self.dict:
            node = self.dict[key]
            self.remove_node(node)
            node.value = value
            self.addTohead(node)
        else:
            # 首先判断是否有位置
            if self.capacity != 0:
                if self.use >= self.capacity:
                    # 删除最不常使用的结点
                    self.dict.pop(self.tail.pre.key)
                    self.remove_node(self.tail.pre)
                    self.use -= 1
                node = Node(key, value)
                self.addTohead(node)
                self.use += 1
                self.dict[key] = node

    def remove_node(self, node):
        node.pre.next = node.next
        node.next.pre = node.pre

    def addTohead(self, node):
        self.head.next.pre = node
        node.next = self.head.next
        node.pre = self.head
        self.head.next = node

双向链表中使用两个哨兵结点来方便操作,同时对链表进行插入和删除的时候,要注意pre和next的赋值顺序

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值