Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f1d0427

Browse files
Add C++ implementation
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent 6d3f3c5 commit f1d0427

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

‎146_lru_cache/lru_cache.cc‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
/**
6+
* Your LRUCache object will be instantiated and called as such:
7+
* LRUCache* obj = new LRUCache(capacity);
8+
* int param_1 = obj->get(key);
9+
* obj->put(key,value);
10+
*/
11+
class LRUCache {
12+
public:
13+
LRUCache(int capacity) {
14+
capacity_ = capacity;
15+
}
16+
17+
int get(int key) {
18+
if (ht_.find(key) == ht_.end()) {
19+
return -1;
20+
}
21+
22+
int value = ht_[key]->second;
23+
if (li_.front().second != value) {
24+
li_.erase(ht_[key]);
25+
li_.push_front(make_pair(key, value));
26+
ht_[key] = li_.begin(); // iterator failure
27+
}
28+
29+
return value;
30+
}
31+
32+
void put(int key, int value) {
33+
if (ht_.find(key) != ht_.end()) {
34+
li_.erase(ht_[key]);
35+
} else {
36+
if (li_.size() == capacity_) {
37+
auto lru = li_.back();
38+
li_.pop_back();
39+
ht_.erase(lru.first);
40+
}
41+
}
42+
li_.push_front(make_pair(key, value));
43+
ht_[key] = li_.begin(); // iterator failure
44+
}
45+
46+
private:
47+
int capacity_;
48+
list<pair<int, int>> li_;
49+
unordered_map<int, pair<int, int>::iterator> ht_;
50+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /