leetcode 146. LRU Cache
题目
手写一个LRU cache
思路和代码
用stl
注意到 list<int>
的begin()
和end()
是iterator
类型的
front()
和back()
是int
类型的
还应该注意到erase
写法
class LRUCache {
public:
LRUCache(int capacity) {
cap = capacity;
}
int get(int key) {
auto it = cache.find(key);
if(it == cache.end())
return -1;
// found it and swap to head;
int value = it->second.first;
v.erase(it->second.second);
v.push_front(key);
cache[key] = make_pair(value, v.begin());
return value;
}
void put(int key, int value) {
auto it = cache.find(key);
if (it == cache.end()) {
// not fount it
int len = cache.size();
if(len == cap) {
// last erase
cache.erase(v.back());
v.pop_back();
}
v.push_front(key);
cache[key] = make_pair(value, v.begin());
} else {
// found it and swap to head;
v.erase(it->second.second);
v.push_front(key);
cache[key] = make_pair(value, v.begin());
}
return ;
}
private:
typedef pair<int, list<int>::iterator> pil;
int cap;
list<int> v;
unordered_map<int, pil> cache;
};