-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path146.lru缓存机制.cpp
80 lines (68 loc) · 1.46 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
* @lc app=leetcode.cn id=146 lang=cpp
*
* [146] LRU缓存机制
*/
// @lc code=start
#include<iostream>
#include<algorithm>
#include<map>
#include<list>
using namespace std;
struct Node{
int key;
int value;
Node(int key, int value){
this->key = key;
this->value = value;
}
Node(){
}
};
class LRUCache {
public:
int capacity;
list<Node*> head;
map<int, Node*> m;
LRUCache(int capacity) {
this->capacity = capacity;
}
int get(int key) {
int value = -1;
if(m.count(key))
{
value = m[key]->value;
put(key, value);
}
return value;
}
void put(int key, int value) {
Node *x = new Node(key, value);
if(m.count(key))
{
//修改节点value
//将节点提到head的位置
head.remove(m[key]);
head.push_front(x);
m[key] = x;
}else{
//新建一个节点
//考虑capacity
if(m.size()== capacity)
{
Node *last = head.back();
m.erase(last->key);
head.pop_back();
}
head.push_front(x);
m[key] = x;
}
}
};
/**
* 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