题目:设计一个最近使用的缓存数据结构,其须支持get和put两种操作
get(key):如果LRU中key存在,则返回其值,否则返回-1;
put(key,value):如果key存在,则改变其值为value,否则插入一个新的key,value。当缓存容量达到上限,需要在插入新的元素之前删去其中最近未使用的元素。
C++实现(C++ 11)https://discuss.leetcode.com/topic/6812/c-11-code-74ms-hash-table-list
class LRUCache {
public:
LRUCache(int capacity) : _capacity(capacity) {}
int get(int key) {
auto it = cache.find(key);
if (it == cache.end()) return -1;
touch(it);
return it->second.first;
}
void set(int key, int value) {
auto it = cache.find(key);
if (it != cache.end()) touch(it);
else {
if (cache.size() == _capacity) {
cache.erase(used.back());
used.pop_back();
}
used.push_front(key);
}
cache[key] = { value, used.begin() };
}
private:
typedef list<int> LI;
typedef pair<int, LI::iterator> PII;
typedef unordered_map<int, PII> HIPII;
void touch(HIPII::iterator it) {
int key = it->first;
used.erase(it->second.second);
used.push_front(key);
it->second.second = used.begin();
}
HIPII cache;
LI used;
int _capacity;
};