#include<unordered_map>
#include<list>
#include<iostream>
using namespace std;
class LRUCache{
public:
unordered_map<int, list<int>::iterator> m;
list<int> priority;
int cap;
int size;
LRUCache(int capacity) {
cap = capacity;
size = 0;
}
int get(int key) {
int val = -1;
auto iter = m.find(key);
if ( iter!= m.end()){
auto cur = iter->second;
val = *cur;
priority.erase(cur);
priority.push_front(val);
m[key] = priority.begin();
}
return val;
}
void set(int key, int value) {
auto cur = m.find(key);
if (cur != m.end()){
auto iter = cur ->second;
priority.erase(iter);
priority.push_front(value);
m[key] = priority.begin();
}
else if (size < cap && cur == m.end()){
size++;
priority.push_front(value);
m[key] = priority.begin();
}
else{
unordered_map<int, list<int>::iterator>::iterator first = m.begin(), last = m.end(), iter;
for (iter = first; iter != last; iter++){
if (iter->second == (--priority.end())){
break;
}
}
m.erase(iter);
priority.pop_back();
priority.push_front(value);
m[key] = priority.begin();
}
}
};
int main(){
LRUCache cache(2);
cache.set(2, 1);
cache.set(2, 2);
cout << cache.get(2) << endl;
cache.set(1, 1);
cache.set(4, 1);
cout << cache.get(2) << endl;
return 0;
}
题目: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.
题目解析:这个题目在于如何设计一个高效的数据结构,实现数据的插入和查找,并且在缓存满了的情况下,采用LRU的策略进行数据的替换。
算法设计中的注意事项:
1.在get()函数的设计中,如何找到对应的value,必须要更改相应的优先级;
2.在set()函数的设计中,需要考虑三种情况:(1)缓存未满的情况;(2)缓存已经满了的情况;(3)还需要考虑set的key已经存在。在这三种都涉及对优先级的更改。
思路:最直接的想法是,直接采用map的数据结构保存<key,value>对,采用链表来记录每个key的优先级。其中,因为链表是一个顺序的容器,可以采用本身的顺序来保存优先级。这个算法的问题在于数据冗余。链表中存储key的话,每次get或set都需要进行o(n)的查找,得到相应的位置。所以,采用这样的设计方法显然比较慢。
那么,如何改进算法来避免存储的冗余并提高查找速度呢?
如果能够直接存储list中对应位置的迭代器,就可以避免O(n)时间的查找,可以用list来存储对应的value,这样也避免了数据的冗余。
在最上面给出了一个参考的代码,对上面描述的思想进行了实现。