Leetcode 146. LRU Cache
2018-02-09 09:10
176 查看
原题:
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:
Follow up:
Could you do both operations in O(1) time complexity?
Example:LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
解题方法:
- 用list保存键值对,最近访问的放在前面,很少访问的会在后面。
- 用哈希表保存键值和list的指针位置。
代码:
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:
getand
put.
get(key)- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(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.
Follow up:
Could you do both operations in O(1) time complexity?
Example:LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
解题方法:
- 用list保存键值对,最近访问的放在前面,很少访问的会在后面。
- 用哈希表保存键值和list的指针位置。
代码:
class LRUCache { int c; unordered_map<int,list<pair<int,int>>::iterator> m; list<pair<int,int>> d; public: LRUCache(int capacity) { c = capacity; } int get(int key) { auto pos = m.find(key); if (pos == m.end()) return -1; int val = pos->second->second; d.erase(pos->second); d.push_front({key, val}); m[key] = d.begin(); return val; } void put(int key, int value) { auto pos = m.find(key); if (pos == m.end()){ if (m.size() >= c){ m.erase(d.back().first); d.pop_back(); } }else{ d.erase(pos->second); } d.push_front({key, value}); m[key] = d.begin(); } };
相关文章推荐
- Leetcode 146. LRU Cache
- 【leetcode】146. LRU Cache【H】【9】
- 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
- leetcode 146. LRU Cache
- LeetCode 146. LRU Cache
- leetcode题解-146. LRU Cache
- Leetcode 146. LRU Cache
- LeetCode-146. LRU Cache
- LeetCode 146. LRU Cache(LRU缓存)
- Leetcode 146. LRU Cache
- LeetCode 146. LRU Cache
- ***Leetcode 146. LRU Cache