题目:
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.
设计一个最近最少使用的数据结构。算法不难,插入一个(key, value),如果capacity是满的,那就把最久未操作的元素删除,这个(key,value)再插进去。代码时参考别人的,list数据结构没有用过,对STL还是不熟。
#include <list>
#include <unordered_map>
using namespace std;
struct CacheNode
{
int key;
int value;
CacheNode(int k, int v): key(k), value(v){}
};
class LRUCache
{
public:
LRUCache(int capacity){
size = capacity;
}
int get(int key){
if (cacheMap.find(key) != cacheMap.end())
{
auto it = cacheMap[key];
cacheList.splice(cacheList.begin(), cacheList, it);
cacheMap[key] = cacheList.begin();
return cacheList.begin()->value;
}
else
return -1;
}
void set(int key, int value){
if (cacheMap.find(key) == cacheMap.end())
{
if (cacheList.size() == size)
{
// 消除对应元素
cacheMap.erase(cacheList.back().key);
cacheList.pop_back();
}
cacheList.push_front(CacheNode(key,value));
cacheMap[key] = cacheList.begin();
}
else
{
auto it =cacheMap[key];
cacheList.splice(cacheList.begin(),cacheList,it);
cacheMap[key] = cacheList.begin();
cacheList.begin()->value = value;
}
}
private:
int size;
list<CacheNode> cacheList;
unordered_map<int, list<CacheNode>::iterator > cacheMap;
};
auto:c++11 增加的一个变量,自动类型推断,如:auto i = 4; 自动推断i为int类型
splice(): list容器中的拼接操作,有三种重载函数:
void splice (iterator position, list& x);
void splice (iterator position, list& x, iterator i);
void splice (iterator position, list& x, iterator first, iterator last);
第一种是,把x中的全部元素插入到list中position之前的位置,同时把x中的所有元素都删除,x和list的大小都发生改变
第二种是,把x中i指向的那个元素插入到list中的position之前的位置,同时把x中的i指向的那个元素删除,x和list的大小都发生改变
第三种和第二种类似,变成范围似的删除.
void advance(InputIterator& it, Distance n)
移动到离迭代器it距离为n的元素,从0开始计数,例如:
for(int i =0; i<10; i++)
mylist.pushback(i);
list<int>::iteraotr it = mylist.begin();
advace(it, 5);
cout<<*it<<endl;
最后输出的元素为5;