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.
每次get或者set的時候, 先將key壓入隊列尾部,然後在哈希表中對應的key的訪問次數+1;
如果滿了,進行while循環:查看隊列頭部的元素, 如果訪問次數>1,則說明後面還被訪問過, 故彈出, 如果訪問次數==1,則說明後面已經沒有被訪問過,所以彈出並且在哈希表中刪掉key。如此, 可以保證做少被訪問的元素被彈出(保證了訪問次數相同的情況下,先進先出)
class LRUCache{
public:
// @param capacity, an integer
LRUCache(int capacity) {
// write your code here
this->capacity = capacity;
}
// @return an integer
int get(int key) {
// write your code here
if (map.find(key) != map.end()) {
que.push(key);
map[key].second++;
return map[key].first;
} else {
return -1;
}
}
// @param key, an integer
// @param value, an integer
// @return nothing
void set(int key, int value) {
// write your code here
que.push(key);
if (map.find(key) != map.end()) {
map[key].first = value;
map[key].second++;
} else {
if (map.size() < capacity) {
map[key] = make_pair(value, 1);
} else {
int least_recently_key = que.front();
while (map[least_recently_key].second > 1) {
map[least_recently_key].second--;
que.pop();
least_recently_key = que.front();
}
que.pop();
//cout<<"erase "<<least_recently_key<<endl;
map.erase(least_recently_key);
map[key] = make_pair(value, 1);
}
}
}
private:
int capacity;
unordered_map<int, pair<int, int>> map;
queue<int> que;
};