forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
57 lines (44 loc) · 1.14 KB
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class LRUCache {
private:
int _cap;
// 双链表:装着 (key, value) 元组
list<pair<int, int>> cache;
// 哈希表:key 映射到 (key, value) 在 cache 中的位置
unordered_map<int, list<pair<int, int>>::iterator> umap;
public:
LRUCache(int capacity) {
_cap = capacity;
}
int get(int key) {
auto iter = umap.find(key);
if(iter == umap.end())return -1;
pair<int,int> kv = *umap[key];
cache.erase(umap[key]);//改
cache.push_front(kv);
umap[key] = cache.begin();
return kv.second;
}
void put(int key, int value) {
auto iter = umap.find(key);
if(iter != umap.end()){ //存在于缓存
cache.erase(umap[key]);
cache.push_front(make_pair(key,value));
umap[key] = cache.begin();
return;
}
//不在缓存中
if(cache.size() == _cap) //满了
{
auto iter = cache.back();
umap.erase(iter.first);
cache.pop_back();
cache.push_front(make_pair(key,value));
umap[key] = cache.begin();
}
else //没满
{
cache.push_front(make_pair(key,value));
umap[key] = cache.begin();
}
}
};