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;
};