@@ -84,7 +84,8 @@ class LRUCache {
8484 }
8585};
8686
87- // using C++ list. got RE for memory corruption though :(
87+ 88+ // using C++ std::list
8889class LRUCache {
8990public:
9091 LRUCache (int capacity) {
@@ -95,27 +96,24 @@ class LRUCache {
9596
9697 int get (int key) {
9798 if (table.find (key) != table.end ()) {
98- auto node = table[key];
99- pair<int , int > entry = *node;
100- entries.erase (node);
101- entries.push_front (entry);
102- return entry.second ;
99+ auto entry = table[key];
100+ entries.splice (entries.begin (), entries, entry);
101+ return entry->second ;
103102 }
104103 return -1 ;
105104 }
106105
107106 void put (int key, int value) {
108- pair<int , int > newEntry = {key, value};
109107 if (table.find (key) != table.end ()) {
110- auto curr = table[key];
111- entries.erase (curr);
108+ entries.erase (table[key]);
112109 } else {
113- if (entries.size () >= capacity) {
110+ if (entries.size () >= capacity) {
114111 pair<int , int > tailEntry = entries.back ();
115- entries.pop_back ();
116112 table.erase (tailEntry.first );
117- }
113+ entries.pop_back ();
114+ }
118115 }
116+ pair<int , int > newEntry = {key, value};
119117 entries.push_front (newEntry);
120118 table[key] = entries.begin ();
121119 }
0 commit comments