File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments