题意理解
设计一个最近最少使用的LRU缓冲机制的类
问题分析
使用STL
hash表unordered_map,双链表list。
list用于缓冲区;map用于查询元素位置:list中存放key,value 对,map存放key和list的迭代器。
双链表可以插入头push_front,删除头pop_front,插入尾push_back,删除尾pop_back,
其他
0801:保证get,put都是o(1),需要查询和任意元素增删改效率都很高,还保持先后顺序。我们知道最快的查询是hash,最快的任意元素增删改是双向链表。重复用key做关键字,利用链表的迭代器只是链表的具体位置。
链接
public:
LRUCache(int capacity) {
cap = capacity;
}
void print() {
cout << "======" << endl;
for (auto pair:buffer) {
cout << pair.first << ' ' << pair.second;
}
cout << endl;
}
int get(int key) {
//cout << "get start" << endl;
//print();
int val = -1;
if (dict.count(key)) {
auto it = dict[key];
val = it -> second;
buffer.erase(it);
buffer.push_front(make_pair(key, val));
dict[key] = buffer.begin();
}
//cout << "get end" << endl;
//print();
return val;
}
void put(int key, int value) {
//cout << "put start" << endl;
//print();
if (dict.count(key)) {
auto it = dict[key];
buffer.erase(it);
buffer.push_front(make_pair(key,value));
dict[key] = buffer.begin();
}
else if (buffer.size() < cap) {
buffer.push_front(make_pair(key,value));
dict[key] = buffer.begin();
}
else {
//获取最后一个key
int old_key = buffer.back().first;
//删除dict中的key
dict.erase(old_key);
//删除buffer最后一个记录
buffer.pop_back();
//插入新记录
buffer.push_front(make_pair(key,value));
//插入(key,新纪录)到dict
dict[key]=buffer.begin();
}
//cout << "put end" << endl;
//print();
}
private:
list<pair<int,int>> buffer;
unordered_map<int,list<pair<int,int>>::iterator> dict;
int cap = 0;
};