-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path146.lru-cache.cpp
More file actions
59 lines (53 loc) · 1.2 KB
/
Copy path146.lru-cache.cpp
File metadata and controls
59 lines (53 loc) · 1.2 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
55
56
57
58
/*
* @lc app=leetcode id=146 lang=cpp
*
* [146] LRU Cache
*/
// @lc code=start
class LRUCache {
public:
list<pair<int, int>> cache;
map<int, list<pair<int, int>>::iterator> keylist;
int size;
LRUCache(int capacity)
{
size = capacity;
}
void update(int key, int value)
{
cache.erase(keylist[key]);
cache.push_front({key, value});
keylist[key] = cache.begin();
}
int get(int key)
{
if (keylist.find(key) != keylist.end())
{
update(key, keylist[key]->second);
return keylist[key]->second;
}
return -1;
}
void put(int key, int value)
{
if (keylist.find(key) != keylist.end())
update(key, value);
else
{
cache.push_front({key, value});
keylist[key] = cache.begin();
if (cache.size() > size)
{
keylist.erase(cache.back().first);
cache.pop_back();
}
}
}
};
/**
* 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);
*/
// @lc code=end