一、题目
题目描述
设计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)变为最不常使用的记录
二、思路
1、用两个函数分别实现set和get;
2、用两个容器同时保存的缓存,一个为vector容器保存key,主要是按插入的顺序保存;另个一个哈希容器,主要是方便根据key查找value,两个容器同时更新维护
3、用一个容器来接收get返回的结果
4、合理利用STL中find()、erase()等函数
三、代码
class Solution
{
public:
/**
* lru design
* @param operators int整型vector<vector<>> the ops
* @param k int整型 the k
* @return int整型vector
*/
vector<int> result;
unordered_map<int, int> Info;
vector<int> LRU(vector<vector<int>> &operators, int k)
{
vector<int> Cache;
for (int i = 0; i < operators.size(); ++i)
{
if (operators[i][0] == 1)
{
set(operators[i][1], operators[i][2], k);
}
else if (operators[i][0] == 2)
{
Cache.emplace_back(get(operators[i][1]));
}
}
return Cache;
}
void set(int key, int value, int k)
{
if (result.size() >= k && Info.find(key) == Info.end())
{
Info.erase(*result.begin());
result.erase(result.begin());
result.emplace_back(key);
Info.emplace(key, value);
}
else if (result.size() >= k && Info.find(key) != Info.end())
{
result.erase(find(result.begin(), result.end(), key));
result.emplace_back(key);
}
else if (result.size() < k && Info.find(key) == Info.end())
{
result.emplace_back(key);
Info.emplace(key, value);
}
else if (result.size() < k && Info.find(key) != Info.end())
{
result.erase(find(result.begin(), result.end(), key));
result.emplace_back(key);
}
}
int get(int key)
{
if (Info.find(key) == Info.end())
{
return -1;
}
else
{
int x = Info[key];
result.erase(find(result.begin(), result.end(), key));
result.emplace_back(key);
Info.erase(Info.find(key));
Info.emplace(key, x);
return x;
}
}
};