题目描述
设计LRU缓存结构,该结构在构造时确定大小,假设大小为K,并有如下两个功能
- set(key, value):将记录(key, value)插入该结构
- get(key):返回key对应的value值
[要求]
- set和get方法的时间复杂度为O(1)
- 某个key的set或get操作一旦发生,认为这个key的记录成了最常使用的。
- 当缓存的大小超过K时,移除最不经常使用的记录,即set或get最久远的。
若opt=1,接下来两个整数x, y,表示set(x, y)
若opt=2,接下来一个整数x,表示get(x),若x未出现过或已被移除,则返回-1
对于每个操作2,输出一个答案
示例1
输入
[[1,1,1],[1,2,2],[1,3,2],[2,1],[1,4,4],[2,2]],3
输出
[1,-1]
说明
第一次操作后:最常使用的记录为("1", 1)
第二次操作后:最常使用的记录为("2", 2),("1", 1)变为最不常用的
第三次操作后:最常使用的记录为("3", 2),("1", 1)还是最不常用的
第四次操作后:最常用的记录为("1", 1),("2", 2)变为最不常用的
第五次操作后:大小超过了3,所以移除此时最不常使用的记录("2", 2),加入记录("4", 4),并且为最常使用的记录,然后("3", 2)变为最不常使用的记录
备注:
思路:
插入和删除时间复杂度为O(1),则用链表存储key,value;查找时间复杂度为O(1),则用hashmap存储,同步更新这两个结构
C++
#include <unordered_map>
class Solution {
public:
/**
* lru design
* @param operators int整型vector<vector<>> the ops
* @param k int整型 the k
* @return int整型vector
*/
int capacity;
list<pair<int, int>> lrulist;//双端队列模拟
unordered_map<int, list<pair<int, int>>::iterator> lrumap;//map的value放的是引用
vector<int> LRU(vector<vector<int> >& operators, int k) {
// write code here
vector<int> res;
capacity = k;
if(operators.empty())
return res;
for(auto it = operators.begin(); it != operators.end(); ++it){
vector<int> temp = *it;
if(temp[0] == 1)
set(temp[1], temp[2]);
else{
res.push_back(get(temp[1]));
}
}
return res;
}
void set(int key, int value){
auto it = lrumap.find(key);
if(it == lrumap.end()){//没找到
if(lrumap.size() == capacity){//满了,删除最久未使用
lrumap.erase(lrulist.back().first);
lrulist.pop_back();
}
}
else//找到了 删除提前
lrulist.erase(it->second);
lrulist.push_front({key, value});
lrumap[key] = lrulist.begin();//begin:返回一个迭代器 front:返回引用
}
int get(int key){
auto it = lrumap.find(key);
if(it == lrumap.end())
return -1;
int val = it->second->second;//找到了,记录值并把它提到最前面
lrulist.erase(it->second);
lrulist.push_front(*it->second);//*迭代器为其指向的元素
return val;
}
};