-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_STOII_0031_LRUCache.cc
111 lines (100 loc) · 1.95 KB
/
Problem_STOII_0031_LRUCache.cc
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
// seem as 0146
// https://leetcode-cn.com/problems/lru-cache/
// see at Problem_0146_LRUCache.cc
class LRUCache
{
private:
class Node
{
public:
Node *pre;
Node *next;
int key;
int val;
Node() : pre(nullptr), next(nullptr), key(0), val(0) {}
Node(int k, int v) : pre(nullptr), next(nullptr), key(k), val(v) {}
Node(Node *p, Node *n, int k, int v) : pre(p), next(n), key(k), val(v) {}
};
void addToHead(Node *node)
{
node->pre = head;
node->next = head->next;
head->next->pre = node;
head->next = node;
}
void removeNode(Node *node)
{
node->pre->next = node->next;
node->next->pre = node->pre;
}
void moveToHead(Node *node)
{
removeNode(node);
addToHead(node);
}
Node *removeTail()
{
Node *node = tail->pre;
removeNode(node);
return node;
}
Node *head;
Node *tail;
int size;
int capacity;
unordered_map<int, Node *> map;
public:
LRUCache(int capacity)
{
// 使用两个伪节点,简化逻辑
head = new Node();
tail = new Node();
head->next = tail;
tail->pre = head;
size = 0;
this->capacity = capacity;
}
int get(int key)
{
if (!map.count(key))
{
return -1;
}
Node *node = map.at(key);
moveToHead(node);
return node->val;
}
void put(int key, int value)
{
if (!map.count(key))
{
Node *node = new Node(key, value);
map[key] = node;
addToHead(node);
++size;
if (size > capacity)
{
Node *rmd = removeTail();
map.erase(rmd->key);
delete rmd;
--size;
}
}
else
{
Node *node = map[key];
node->val = value;
moveToHead(node);
}
}
};
/**
* 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);
*/