146. LRU Cache hash+链表
来源:互联网 发布:网络运营商排行榜 编辑:程序博客网 时间:2024/05/12 23:18
题目地址
使用了一个hash表和一个链表,每次访问元素(get)或是添加元素都将元素置于链表的头部,尾部的自然就是最久未使用的。
hash表存储元素在链表中的位置,链表储存key-value,以方便超出容量时从hash表移除旧元素。
class LRUCache {public: unordered_map<int, list<pair<int, int>>::iterator> ump; list<pair<int, int>> values; int size; LRUCache(int capacity) { size = capacity; } int get(int key) { if (ump.count(key)) { auto now = *ump[key]; int value = now.second; values.erase(ump[key]); values.push_front(now); ump[key] = values.begin(); return value; } return -1; } void put(int key, int value) { if (ump.count(key)) { values.erase(ump[key]); } values.push_front(make_pair(key, value)); ump[key] = values.begin(); if (values.size() > size) { pair<int, int> end = (pair<int, int> &&) values.back(); ump.erase(end.first); values.pop_back(); } }};/** * Your LRUCache object will be instantiated and called as such: * LRUCache obj = new LRUCache(capacity); * int param_1 = obj.get(key); * obj.put(key,value); */
0 0
- 146. LRU Cache hash+链表
- [leetcode] 【链表】 146. LRU Cache
- LeetCode 146. LRU Cache
- [leetcode] 146.LRU Cache
- 146. LRU Cache
- leetcode 146. LRU Cache
- Leetcode 146. LRU Cache
- Leetcode - 146. LRU Cache
- Leetcode 146. LRU Cache
- [leetcode] 146. LRU Cache
- Leetcode 146. LRU Cache
- leetcode 146. LRU Cache
- LeetCode-146. LRU Cache
- LeetCode 146. LRU Cache
- 146. LRU Cache
- LeetCode 146. LRU Cache
- 146. LRU Cache
- 146. LRU Cache
- 程序员对知识管理的思考
- CentOS 7.2部署MariaDB主从复制架构
- ASP调试程序问题解决:ADODB.Connection 错误 '800a0e7a' 未找到提供程序。该程序可能未正确安装
- 面向对象静态代码,构造代码执行顺序
- react native 开发框架,封装网络请求,自定义控件,常用工具类
- 146. LRU Cache hash+链表
- androidstudio创建animtaion-list文件及创建帧动画
- [LeetCode]481. Magical String
- 跳表的实现
- Java 通过 JNI 调用 C/C++ 类库
- codeforces-140【A几何】【精度】
- .NET Core 1.1日期解析无APi、SQL Server数据转换JSON
- 面向对象 单例
- datatable插件使用