-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRU Cache.cpp
More file actions
50 lines (44 loc) · 1.44 KB
/
LRU Cache.cpp
File metadata and controls
50 lines (44 loc) · 1.44 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
//Space Complexity: O(n)
//int get(int key); Time complexity: O(1)
//void put(int key, int value); Time complexity: O(1)
class LRUCache {
public:
list<int> l;
unordered_map<int, pair<int, list<int>::iterator>> mp; // map: key -> (value, iterator)
int cap;
LRUCache(int capacity) {
cap = capacity;
}
int get(int key) {
if (mp.find(key) == mp.end()) return -1;
// get the key's current information
auto pos = mp[key].second;
int val = mp[key].first;
// update the key's information
l.push_front(key);
l.erase(pos);
mp[key].second = l.begin();
return val;
}
void put(int key, int value) {
// use get(key) to check if key exists in the list;
//if yes, the information of the key is updated already;
int vtemp = get(key);
if (vtemp == -1) { // if no
if (l.size() == cap) { // erase the least recent key
int lastKey = l.back();
l.pop_back();
mp.erase(lastKey);
}
l.push_front(key); // put the key to the front of the list
mp[key].second = l.begin();
}
mp[key].first = value;
}
};
/**
* 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);
*/