forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path146.LRU-Cache.cpp
More file actions
54 lines (45 loc) · 1.13 KB
/
Copy path146.LRU-Cache.cpp
File metadata and controls
54 lines (45 loc) · 1.13 KB
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
class LRUCache {
unordered_map<int,int>key2val;
list<int>List;
unordered_map<int, list<int>::iterator>key2iter;
int cap;
public:
LRUCache(int capacity) {
cap = capacity;
}
int get(int key)
{
if (key2val.find(key)==key2val.end())
return -1;
auto iter = key2iter[key];
List.erase(iter);
List.push_back(key);
key2iter[key] = --List.end();
return key2val[key];
}
void put(int key, int value)
{
if (get(key)!=-1)
{
key2val[key] = value;
return;
}
if (key2val.size()==cap)
{
int keyDel = *List.begin();
key2val.erase(keyDel);
key2iter.erase(keyDel);
List.erase(List.begin());
}
key2val[key] = value;
List.push_back(key);
key2iter[key] = --List.end();
}
};
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
//key1, key3, ..., key_n, key2,