1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| #include <iostream> #include <unordered_map> #include <list> #include <algorithm> #include <utility>
using namespace std;
class LRUCache { private: unordered_map<int, list<pair<int, int> >::iterator > cache_map; list<pair<int, int> > cache_list; int cap; public: LRUCache(int cap_v) : cap(cap_v) {} void put(int key, int val) { unordered_map<int, list<pair<int, int> >::iterator >::iterator it = cache_map.find(key); if (it != cache_map.end()) { list<pair<int, int> >::iterator del = it->second; del->second = val; pair<int, int> tmp = *del; cache_list.erase(del); cache_list.push_front(tmp);
cache_map[key] = cache_list.begin();
} else { pair<int, int> tmp = make_pair(key, val); if (cache_map.size() >= cap) { int del_key = cache_list.back().first; cache_list.pop_back(); unordered_map<int, list<pair<int, int> >::iterator>::iterator del_it = cache_map.find(del_key); cache_map.erase(del_it); } cache_list.push_front(tmp); cache_map[key] = cache_list.begin(); } } int get(int key) { int ret_val = -1; unordered_map<int, list<pair<int, int> >::iterator >::iterator it = cache_map.find(key); if (it != cache_map.end()) { ret_val = it->second->second; list<pair<int, int> >::iterator del = it->second; pair<int, int> tmp = *del; cache_list.erase(del); cache_list.push_front(tmp); cache_map[key] = cache_list.begin(); } return ret_val; } };
int main() { LRUCache cache( 2 ); cache.put(1, 1); cache.put(2, 2); cout << cache.get(1) << endl; cache.put(3, 3); cout << cache.get(2) << endl; cache.put(4, 4); cout << cache.get(1) << endl; cout << cache.get(3) << endl; cout << cache.get(4) << endl; cout << "Hello World!" << endl; }
|