您的位置:首页 > 其它

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: 
get
 and
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 cplusplus