File tree 2 files changed +53
-0
lines changed
2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ 146. LRU Cache
3
+
4
+ Submitted: December 21, 2024
5
+
6
+ Runtime: 71 ms (beats 78.21%)
7
+ Memory: 182.15 MB (beats 27.80%)
8
+ */
9
+
10
+ class LRUCache {
11
+ private:
12
+ const int capacity;
13
+ unordered_map<int , list<pair<int , int >>::iterator> map;
14
+ list<pair<int , int >> list;
15
+ public:
16
+ LRUCache (int capacity) : capacity(capacity) {}
17
+
18
+ int get (int key) {
19
+ if (map.count (key)) {
20
+ int val = (*map[key]).second ;
21
+ list.erase (map[key]);
22
+ list.push_front ({ key, val });
23
+ map[key] = list.begin ();
24
+ return val;
25
+ }
26
+ return -1 ;
27
+ }
28
+
29
+ void put (int key, int value) {
30
+ if (map.count (key)) {
31
+ list.erase (map[key]);
32
+ list.push_front ({ key, value });
33
+ map[key] = list.begin ();
34
+ } else {
35
+ if (list.size () == capacity) {
36
+ map.erase (list.back ().first );
37
+ list.pop_back ();
38
+ }
39
+ list.push_front ({ key, value });
40
+ map[key] = list.begin ();
41
+ }
42
+ }
43
+ };
44
+
45
+ /* *
46
+ * Your LRUCache object will be instantiated and called as such:
47
+ * LRUCache* obj = new LRUCache(capacity);
48
+ * int param_1 = obj->get(key);
49
+ * obj->put(key,value);
50
+ */
Original file line number Diff line number Diff line change @@ -5,6 +5,9 @@ Submitted: November 30, 2024
5
5
6
6
Runtime: 67 ms (beats 85.54%)
7
7
Memory: 173.16 MB (beats 55.15%)
8
+
9
+ A solution for this problem using the std::list class rather than a custom
10
+ LinkedList class is contained within `0146-lru-cache-stl.cpp`.
8
11
*/
9
12
10
13
class LinkedList {
You can’t perform that action at this time.
0 commit comments