博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LintCode] LRU Cache 缓存器
阅读量:6992 次
发布时间:2019-06-27

本文共 1266 字,大约阅读时间需要 4 分钟。

 

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.

 

LeetCode上的原题,请参加我之前的博客。

 

class LRUCache{public:    // @param capacity, an integer    LRUCache(int capacity) {        size = capacity;    }        // @return an integer    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;    }    // @param key, an integer    // @param value, an integer    // @return nothing    void set(int key, int value) {        auto it = m.find(key);        if (it != m.end()) l.erase(it->second);        l.push_front({key, value});        m[key] = l.begin();        if (m.size() > size) {            int t = l.rbegin()->first;            l.pop_back();            m.erase(t);        }    }private:    int size;    list
> l; unordered_map
>::iterator> m;};

 

转载地址:http://pmbvl.baihongyu.com/

你可能感兴趣的文章
排查数据库性能的常用sql语句
查看>>
全排列
查看>>
Node.js&NPM的安装与配置(转)
查看>>
C# CRC16 查表法
查看>>
js中获取键盘事件
查看>>
面试(4)-spring-Spring面试题和答案
查看>>
请教 JTable 里的单元格如何使得双击进入单元格后,单元格的内容处于全选中状态...
查看>>
jQuery 各类判断函数汇总
查看>>
Android studio 分32位64位版本吗?
查看>>
UIcollectionView的使用(首页的搭建1)
查看>>
[原创]AM3352 + TPS65910 调试方法+调试记录
查看>>
.net基本数据类型操作
查看>>
docker 应用-2(Dockerfile 编写以及镜像保存提交)
查看>>
监控 Linux 性能的 18 个命令行工具
查看>>
3000本IT书籍下载地址
查看>>
VS2017 WinFrom打包设置与教程
查看>>
Cannot change version of project facet Dynamic Web Module to 3.0 requires Java 1.6 or newer 解决方案...
查看>>
数据库修改一个表中的字段值等于另一个表字段值
查看>>
mongodb pymongo.errors.CursorNotFound: Cursor not found, cursor id: 82792803897
查看>>
《Spring Security3》第四章第三部分翻译下(密码加salt)
查看>>