Skip to content

Commit d999e0f

Browse files
authored
Create 146. LRU Cache.cpp
1 parent 605bb29 commit d999e0f

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

C++/146. LRU Cache.cpp

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class LRUCache {
2+
public:
3+
LRUCache(int capacity) {
4+
this->capacity = capacity;
5+
}
6+
7+
int get(int key) {
8+
if(!m.count(key) || m[key] == -1) return -1;
9+
q.push_back(key);
10+
visited[key]++;
11+
return m[key];
12+
}
13+
14+
void put(int key, int value) {
15+
if(!m.count(key)|| m[key] == -1) count++;
16+
else visited[key]++;
17+
if(count > capacity){
18+
while(visited[q.front()]) visited[q.front()]--, q.pop_front();
19+
m[q.front()] = -1;
20+
q.pop_front();
21+
count--;
22+
}
23+
q.push_back(key);
24+
m[key] = value;
25+
}
26+
27+
private:
28+
unordered_map<int, int>m;
29+
unordered_map<int, int>visited;
30+
deque<int>q;
31+
int count = 0;
32+
int capacity = 0;
33+
};
34+
35+
/**
36+
* Your LRUCache object will be instantiated and called as such:
37+
* LRUCache obj = new LRUCache(capacity);
38+
* int param_1 = obj.get(key);
39+
* obj.put(key,value);
40+
*/

0 commit comments

Comments
 (0)