自己输入测试用例,纯手写实现:
#include#include #include #include #include #include #include
using namespace std; //Least Recently Used class LRU { private: int cap; list >cache; unordered_map >::iterator>map; public: LRU(int cap) { this->cap = cap; } void get(int key) { if (map.find(key) != map.end()) { auto key_value = *map[key]; cache.erase(map[key]); cache.push_front(key_value); map[key] = cache.begin(); cout << key_value.second << endl; } else { cout << -1 << endl; } } void put(int key,int value){ if (map.find(key) == map.end()) { if (cache.size() == cap) { map.erase(cache.back().first); cache.pop_back(); } cache.push_front({ key,value}); map[key] = cache.begin(); } else { cache.erase(map[key]); cache.push_front({ key,value }); map[key] = cache.begin(); } } }; int main() { LRU* lru = new LRU(3); lru->put(1, 1); lru->put(2, 2); lru->put(3, 3);//<3,3>-><2,2>-><1,1> lru->get(1);//查询到1后调整链表:<1,1>-><3,3>-><2,2> lru->put(4, 4);//<4,4>-><1,1>-><3,3> lru->get(2);//返回-1 }



