[LeetCode]LRU Cache
来源:互联网 发布:网络语音监控 编辑:程序博客网 时间:2024/06/16 19:04
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.
用unordered_map 哈希来实现O(1)的查询。
用双向队列来实现O(1)的头尾删除和指定点的删除。
写起来有些复杂,队列越前面表示最近用的多。每当set一个新节点时要放倒队列前面,同时超过容量时删除队尾的元素。所以双向队列最好。
class LRUCache{public: struct Cache{ int key; int value; Cache(int a,int b):key(a),value(b){} }; LRUCache(int capacity) { this->capacity = capacity; } int get(int key) { if(cacheMap.find(key)==cacheMap.end()) return -1; //没有找到节点 //找到节点最近使用放在最前面 else{ int ret = cacheMap[key]->value; cacheList.erase(cacheMap[key]); cacheList.push_front(Cache(key,ret)); cacheMap[key]= cacheList.begin(); return ret; } } void set(int key, int value) { //赋值要更新,如果不是赋值是插入要插到最前面,同时注意不要超过容量 if(cacheMap.find(key)==cacheMap.end()){ //插入 if(cacheList.size()!=capacity){ //没有超过容量,记得同步更新Map cacheList.push_front(Cache(key,value)); cacheMap[key] = cacheList.begin(); } else{ //超出容量 cacheList.push_front(Cache(key,value)); cacheMap.erase(cacheList.back().key); cacheList.pop_back(); cacheMap[key] = cacheList.begin(); } } else{ //更新值 cacheList.erase(cacheMap[key]); //删除当前节点,赋值更新要插入到最前面 cacheList.push_front(Cache(key,value)); cacheMap[key] = cacheList.begin(); } }private: list<Cache> cacheList; //前插,删除时间也为O(1) unordered_map<int, list<Cache>::iterator> cacheMap; //保证查找速度为O(1),map一个int和cache迭代器 int capacity;};
0 0
- LeetCode LRU 缓存 LRU Cache
- LRU Cache | leetcode
- Leetcode: LRU Cache
- LeetCode:LRU Cache
- Leetcode: LRU Cache
- [LeetCode] LRU Cache
- leetcode之LRU Cache
- [LeetCode]LRU Cache
- [LeetCode] LRU Cache
- leetcode LRU Cache
- LeetCode题解:LRU Cache
- LeetCode | LRU Cache
- Leetcode: LRU Cache
- [LeetCode] LRU Cache
- LeetCode OJ:LRU Cache
- Leetcode LRU Cache
- LeetCode - LRU Cache
- [Leetcode] LRU Cache (Java)
- Android之Adapter用法总结
- 热点板块黑马
- 乘积最大(动规例题)
- Unity3d SendMessage 简单用法笔记
- Linux/Windows 环境下openGL开发环境问题集锦
- [LeetCode]LRU Cache
- 最小生成树
- 【C++】C++对象内存模型简介
- iOS Masonry的使用详解
- 【NOIP2015模拟11.3】备用钥匙
- HDU 3625 Examining the Rooms (第一类斯特灵数,组合数学)
- 安卓010 Content Provider
- 发现的一个视频数据集
- [杂记]国内某两家IT公司面试经验