-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathP146.cpp
64 lines (57 loc) · 1.52 KB
/
P146.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
#include<bits/stdc++.h>
using namespace std;
class LRUCache {
public:
using KV = pair<int, int>;
LRUCache(int capacity) {
capacity_ = capacity;
}
int get(int key) {
auto res = hashtable_.find(key);
if (res == hashtable_.end())
{
return -1;
}
else
{
int value = res->second->second;
table_.erase(res->second);
table_.emplace_back(key, value);
auto itr = table_.end();
res->second = --itr;
return value;
}
}
void put(int key, int value) {
auto res = hashtable_.find(key);
if (res == hashtable_.end())
{
table_.emplace_back(key, value);
list<KV>::iterator itr = table_.end();
hashtable_[key] = --itr;
if (table_.size() > capacity_)
{
auto k = table_.front();
hashtable_.erase(hashtable_.find(k.first));
table_.pop_front();
}
}
else
{
table_.erase(res->second);
table_.emplace_back(key, value);
list<KV>::iterator itr = table_.end();
res->second= --itr;
}
}
private:
int oldest_, capacity_;
list<KV> table_;
unordered_map<int, list<KV>::iterator> hashtable_;
};
/**
* 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);
*/