Day34.LRU缓存机制

题目描述:

运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。

写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,从而为新的数据值留出空间。

示例:

LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // 返回  1
cache.put(3, 3);    // 该操作会使得密钥 2 作废
cache.get(2);       // 返回 -1 (未找到)
cache.put(4, 4);    // 该操作会使得密钥 1 作废
cache.get(1);       // 返回 -1 (未找到)
cache.get(3);       // 返回  3
cache.get(4);       // 返回  4

测试用例:

在这里插入图片描述

代码如下:

class LRUCache():
    def __init__(self, capacity):
        """
        :type capacity: int
        """
        self.capacity = capacity
        self.num = {}
        self.fir = []
        
    def get(self, key):
        """
        :type key: int
        :rtype: int
        """
        if key not in self.num:
            return -1
        else:
            self.fir.remove(key)
            self.fir.append(key)
            return self.num[key]
              
     def put(self, key, value):
        """
        :type key: int
        :type value: int
        :rtype: None
        """
        if key not in self.num:
            if len(self.num) >= self.capacity:
                self.num.pop(self.fir[0])
                self.fir.pop(0)
        else:
            self.fir.remove(key)
        self.num[key] = value
        self.fir.append(key)

在这里插入图片描述

发布了71 篇原创文章 · 获赞 4 · 访问量 1101

猜你喜欢

转载自blog.csdn.net/qq_44957388/article/details/101616198
今日推荐