请你设计并实现一个满足 LRU(最近最少使用)缓存约束的数据结构。
实现 LRUCache 类:
-
LRUCache(int capacity):以正整数capacity初始化 LRU 缓存。 -
int get(int key):如果关键字key存在于缓存中,则返回其值,否则返回-1。 -
void put(int key, int value):如果关键字key已存在,则变更其值为value;如果不存在,则插入该键值对。如果插入导致容量超出,则逐出最久未使用的关键字。
输入描述
第一行输入一个整数 capacity。
第二行输入一个整数 m,表示操作次数。
接下来 m 行,每行输入一个操作:
-
get key -
put key value
输出描述
对于每个 get 操作,输出查询结果。
示例 1
输入
text
2
5
put 1 1
put 2 2
get 1
put 3 3
get 2
输出
text
1
-1
C++ 解法
cpp
#include <bits/stdc++.h>
using namespace std;
class LRUCache {
private:
int cap;
list<pair<int,int>> cache;
unordered_map<int, list<pair<int,int>>::iterator> mp;
public:
LRUCache(int capacity) : cap(capacity) {}
int get(int key) {
if (!mp.count(key)) return -1;
auto it = mp[key];
int value = it->second;
cache.erase(it);
cache.push_front({key, value});
mp[key] = cache.begin();
return value;
}
void put(int key, int value) {
if (mp.count(key)) {
cache.erase(mp[key]);
} else if ((int)cache.size() >= cap) {
int oldKey = cache.back().first;
cache.pop_back();
mp.erase(oldKey);
}
cache.push_front({key, value});
mp[key] = cache.begin();
}
};
int main() {
int capacity;
cin >> capacity;
int m;
cin >> m;
LRUCache lru(capacity);
while (m--) {
string op;
cin >> op;
if (op == "get") {
int key;
cin >> key;
cout << lru.get(key) << endl;
} else if (op == "put") {
int key, value;
cin >> key >> value;
lru.put(key, value);
}
}
return 0;
}