[LeetCode] LRU Cache 最近最少使用页面置换缓存器

简介:

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

这道题让我们实现一个LRU缓存器,LRU是Least Recently Used的简写,就是最近最少使用的意思。那么这个缓存器主要有两个成员函数,get和set,其中get函数是通过输入key来获得value,如果成功获得后,这对(key, value)升至缓存器中最常用的位置(顶部),如果key不存在,则返回-1。而set函数是插入一对新的(key, value),如果原缓存器中有该key,则需要先删除掉原有的,将新的插入到缓存器的顶部。如果不存在,则直接插入到顶部。若加入新的值后缓存器超过了容量,则需要删掉一个最不常用的值,也就是底部的值。具体实现时我们需要三个私有变量,cap, l和m,其中cap是缓存器的容量大小,l是保存缓存器内容的列表,m是哈希表,保存关键值key和缓存器各项的迭代器之间映射,方便我们以O(1)的时间内找到目标项。

然后我们再来看get和set如何实现,get相对简单些,我们在m中查找给定的key,如果存在则将此项移到顶部,并返回value,若不存在返回-1。对于set,我们也是现在m中查找给定的key,如果存在就删掉原有项,并在顶部插入新来项,然后判断是否溢出,若溢出则删掉底部项(最不常用项)。代码如下:

class LRUCache{
public:
    LRUCache(int capacity) {
        cap = capacity;
    }
    
    int get(int key) {
        auto it = m.find(key);
        if (it == m.end()) return -1;
        l.splice(l.begin(), l, it->second);
        return it->second->second;
    }
    
    void set(int key, int value) {
        auto it = m.find(key);
        if (it != m.end()) l.erase(it->second);
        l.push_front(make_pair(key, value));
        m[key] = l.begin();
        if (m.size() > cap) {
            int k = l.rbegin()->first;
            l.pop_back();
            m.erase(k);
        }
    }
    
private:
    int cap;
    list<pair<int, int> > l;
    unordered_map<int, list<pair<int, int> >::iterator> m;
};

本文转自博客园Grandyang的博客,原文链接:最近最少使用页面置换缓存器[LeetCode] LRU Cache ,如需转载请自行联系原博主。

相关文章
|
30天前
|
缓存 算法 Java
Caffeine Cache~高性能 Java 本地缓存之王
Caffeine Cache~高性能 Java 本地缓存之王
51 1
|
1月前
|
存储 缓存 Java
【Spring原理高级进阶】有Redis为啥不用?深入剖析 Spring Cache:缓存的工作原理、缓存注解的使用方法与最佳实践
【Spring原理高级进阶】有Redis为啥不用?深入剖析 Spring Cache:缓存的工作原理、缓存注解的使用方法与最佳实践
|
3月前
|
缓存 NoSQL Java
Spring Cache 缓存原理与 Redis 实践
Spring Cache 缓存原理与 Redis 实践
141 0
|
3月前
|
存储 缓存 NoSQL
把ruoyi-vue前后端分离项目的redis缓存改为本地缓存cache
把ruoyi-vue前后端分离项目的redis缓存改为本地缓存cache
148 0
|
21天前
|
存储 XML 缓存
【深入浅出Spring原理及实战】「缓存Cache开发系列」带你深入分析Spring所提供的缓存Cache功能的开发实战指南(一)
【深入浅出Spring原理及实战】「缓存Cache开发系列」带你深入分析Spring所提供的缓存Cache功能的开发实战指南
42 0
|
1月前
|
缓存 NoSQL Java
spring cache整合redis实现springboot项目中的缓存功能
spring cache整合redis实现springboot项目中的缓存功能
45 1
|
1月前
|
存储 缓存 算法
深入探究LRU缓存机制:优化内存利用与提升性能
深入探究LRU缓存机制:优化内存利用与提升性能
114 1
|
1月前
|
缓存
LRU 缓存置换策略:提升系统效率的秘密武器(下)
LRU 缓存置换策略:提升系统效率的秘密武器(下)
|
1月前
|
存储 缓存 算法
LRU 缓存置换策略:提升系统效率的秘密武器(上)
LRU 缓存置换策略:提升系统效率的秘密武器(上)
|
2月前
|
缓存 监控 安全
如何使用LRU缓存来提高程序的性能?
如何使用LRU缓存来提高程序的性能?
20 3