-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache.cpp
More file actions
55 lines (54 loc) · 1.6 KB
/
Copy pathLRUCache.cpp
File metadata and controls
55 lines (54 loc) · 1.6 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
#include<unordered_map>
#include<list>
/*struct compare{
bool operator()(const std::pair<int,int> &p1, const std::pair<int,int>& p2){
//first one is key and second one is frequency;
//page with least frequency will be poped out
//use min Heap on second value of pairs
return p1.second>p2.second;
}
};*/
class LRUCache {
private:
int capacity;
//store key and value
std::unordered_map<int,int> hashMap;
std::list<int> lst;
public:
LRUCache(int _capacity) {
capacity = _capacity;
}
int get(int key) {
if(hashMap.find(key)==hashMap.end()){
//key not in frame;
return -1;
}
lst.remove(key);
lst.push_front(key);
return hashMap[key];
}
void put(int key, int value) {
if(hashMap.find(key)!=hashMap.end()){
//hashMap has the value;
hashMap[key] = value;
lst.remove(key);
lst.push_front(key);
return;
}
//hashMap do not have key;
hashMap[key] = value;
if(hashMap.size()>capacity){
//need to remove the minimum used element
int lastVal = lst.back();
hashMap.erase(lastVal);
lst.pop_back();
}
lst.push_front(key);
}
};
/**
* 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);
*/