-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path146. LRU Cache.cpp
More file actions
66 lines (62 loc) · 1.85 KB
/
146. LRU Cache.cpp
File metadata and controls
66 lines (62 loc) · 1.85 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
59
60
61
62
63
64
65
66
struct Node
{
int key;
int value;
};
class LRUCache{
public:
LRUCache(int capacity)
{
maxSize = capacity;
}
int get(int key)
{
map<int, list<Node>::iterator>::iterator it = mp.find(key);
if(it == mp.end()) //没有命中
{
return -1;
}
else //在cache中命中了
{
list<Node>::iterator listIt = mp[key];
Node newNode;
newNode.key = key;
newNode.value = listIt->value;
cacheList.erase(listIt); //先删除命中的节点
cacheList.push_front(newNode); //将命中的节点放到链表头部
mp[key] = cacheList.begin();
}
return cacheList.begin()->value;
}
void set(int key, int value)
{
map<int, list<Node>::iterator >::iterator it = mp.find(key);
if(it == mp.end()) //没有命中
{
if(cacheList.size() == maxSize) //cache满了
{
mp.erase(cacheList.back().key);
cacheList.pop_back();
}
Node newNode;
newNode.key = key;
newNode.value = value;
cacheList.push_front(newNode);
mp[key] = cacheList.begin();
}
else //命中
{
list<Node>::iterator listIt = mp[key];
cacheList.erase(listIt); //先删除命中的节点
Node newNode;
newNode.key = key;
newNode.value = value;
cacheList.push_front(newNode); //将命中的节点放到链表头部
mp[key] = cacheList.begin();
}
}
private:
int maxSize ;
list<Node> cacheList;
map<int, list<Node>::iterator> mp;
};