Leetcode LRU Cache 解题报告
2014-08-15 07:32
549 查看
这道题我用的是一个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。
暂且这样吧。需要重写。
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; }
相关文章推荐
- 2015.03.28 leetcode LRU cache 解题记录
- leetCode解题报告之Sort List
- Leetcode 104. Maximum Depth of Binary Tree 二叉树的最大高度 解题报告
- 【LeetCode】495.Teemo Attacking解题报告
- [leetcode] 239. Sliding Window Maximum 解题报告
- 【LeetCode】Lowest Common Ancestor of a Binary Search Tree 解题报告
- LeetCode 解题报告 Sort List
- LeetCode 136. Single Number 解题报告
- 【LeetCode】553. Optimal Division 解题报告(Python)
- 【LeetCode】Reverse Words in a String 解题报告
- Leetcode 399. Evaluate Division 除法推理 解题报告
- [Leetcode] 104. Maximum Depth of Binary Tree 解题报告
- LeetCode-Factorial Trailing Zeroes-解题报告
- LeetCode-Fraction to Recurring Decimal-解题报告
- LeetCode 199. Binary Tree Right Side View 解题报告
- [Leetcode] 736. Parse Lisp Expression 解题报告
- [leetcode] 322. Coin Change 解题报告
- [LeetCode]414. Third Maximum Number 解题报告
- [Leetcode] 464. Can I Win 解题报告
- leetCode解题报告之构造二叉树(递归)