-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path146.lru-缓存机制.cpp
61 lines (54 loc) · 1.24 KB
/
146.lru-缓存机制.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
58
59
60
61
/*
* @lc app=leetcode.cn id=146 lang=cpp
*
* [146] LRU 缓存机制
*/
// @lc code=start
class LRUCache
{
private:
int cap;
std::list<std::pair<int, int>> NodeList;
std::unordered_map<int, std::list<std::pair<int, int>>::iterator> NodeMap;
public:
LRUCache(int capacity)
{
cap = capacity;
}
int get(int key)
{
auto it = NodeMap.find(key);
if (it == NodeMap.end())
{
return -1;
}
auto kv = (*it->second);
NodeList.erase(it->second);
NodeList.push_front(kv);
it->second = NodeList.begin();
return kv.second;
}
void put(int key, int value)
{
auto it = NodeMap.find(key);
if (it != NodeMap.end())
{
NodeList.erase(it->second);
}
else if (NodeMap.size() >= cap)
{
auto itt = NodeList.rbegin();
NodeMap.erase(itt->first);
NodeList.pop_back();
}
NodeList.push_front({key, value});
NodeMap[key] = NodeList.begin();
}
};
/**
* 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