Leetcode LRU Cache 解题报告
来源:互联网 发布:帝国cms免费吗 编辑:程序博客网 时间:2024/06/01 08:40
这道题我用的是一个hashmap(unordered_map)记录(key, value)pair,用一个数组(vector)记录key的最近使用顺序。这样能够实现功能,但get和set操作都需要O(n)的时间复杂度,因为需要更新那个数组。看了别人的解法,最好的应该是用一个双向链表记录(key, value)pair,同时用一个hashmap记录每个key在双向链表中的位置,这样O(1)的时间就可以定位,并更新。http://www.programcreek.com/2013/03/leetcode-lru-cache-java/有非常简洁的实现。http://fisherlei.blogspot.com/2013/11/leetcode-lru-cache-solution.html也是。
Java中有个linkedhashmap,里面是按照access order排序的,完全符合这个题目的要求,之前实现过,也能通过测试,具体见http://blog.csdn.net/whuwangyi/article/details/15495845。
暂且这样吧。需要重写。
#include <iostream>#include <vector>#include <unordered_map>#include <cassert>using namespace std;class LRUCache{private:unordered_map<int, int> dict;int capacity;std::vector<int> keys;public:LRUCache(int capacity) {this->capacity = capacity;}void updatekey(int key){int index = 0;while (index != keys.size() && keys[index] != key){index++;}assert(index != keys.size());for (int i = index; i + 1 < keys.size(); ++i){keys[i] = keys[i + 1];}keys[keys.size() - 1] = key;}int get(int key) {if (dict.find(key) == dict.end()){return -1;}int value = dict[key];updatekey(key);return value;}void set(int key, int value) {if (dict.find(key) == dict.end()){if (keys.size() == capacity){dict.erase(keys[0]);for (int i = 0; i + 1 < keys.size(); ++i){keys[i] = keys[i + 1];}keys.pop_back();}dict[key] = value;keys.push_back(key);}else{updatekey(key);dict[key] = value;}}};int main(){LRUCache lru(2);lru.set(1, 1);lru.set(2, 2);// cout<<lru.get(1)<<endl;lru.set(3, 3);// cout<<lru.get(1)<<endl;// cout<<lru.get(2)<<endl;// cout<<lru.get(3)<<endl;lru.set(4, 4);cout<<lru.get(1)<<endl;cout<<lru.get(2)<<endl;cout<<lru.get(3)<<endl;cout<<lru.get(4)<<endl;return 0;}
0 0
- Leetcode LRU Cache 解题报告
- 【LeetCode】LRU Cache 解题报告
- LeetCode 解题报告 LRU Cache
- LeetCode—LRU Cache解题报告
- [LeetCode OJ] LRU Cache 解题报告
- [leetcode] 146. LRU Cache 解题报告
- [Leetcode] 146. LRU Cache 解题报告
- LRU算法&&LeetCode解题报告
- 2015.03.28 leetcode LRU cache 解题记录
- leetcode解题笔记:146. LRU Cache
- [Leetcode] 460. LFU Cache 解题报告
- LeetCode LRU 缓存 LRU Cache
- LRU Cache | leetcode
- Leetcode: LRU Cache
- LeetCode:LRU Cache
- Leetcode: LRU Cache
- [LeetCode] LRU Cache
- leetcode之LRU Cache
- 测试设计及自动化全景图
- S5PV210:支持NAND启动u-boot
- 进程、应用程序与域、线程
- 如何采用绝对坐标的方式动画方式移动view和如何点击view的时候获取它的cachebitmap并移动
- 路径规划的MATLAB实现
- Leetcode LRU Cache 解题报告
- Cocos2D-X射击小游戏(十)编码8 游戏流程优化
- python list 操作 增删查
- Python 可视化Facebook用户友谊图
- 使用C++拓展QML 类型及Property binding!
- 点击按钮创建window窗体,窗体重复创建问题
- 第一次开通技术博客
- Test_NOTE
- ubuntu卸载openfire