Untitled
unknown
plain_text
a year ago
1.8 kB
6
Indexable
class LRUCache { public: LRUCache(int capacity) { cap = capacity; } int get(int key) { int count = kCount[key]; auto it = kv[key]; auto [_, value] = kv[key]; countKV[count].erase(it); countKV[count+1].push_back({key, value}); kCount[key] = count + 1; kv[key] = countKV[count+1][countKV[count+1].size() - 1]; // need iter if (countKV[count].size() == 0 && minCount == count) { minCount++; } return value; } // int minCount; // unordered_map<int, vector<pair<int,int>>> countKV; // unordered_map<int, vector<pair<int,int>>::iterator> kv; // unordered_map<int, int> kCount; void put(int key, int value) { if (kv.count(key)) { int count = kCount[key]; auto it = kv[key]; countKV[count].erase(it); countKV[count+1].push_back({key, value}); kCount[key] = count + 1; kv[key] = countKV[count+1][countKV[count+1].size() - 1]; // need iter if (countKV[count].size() == 0 && minCount == count) { minCount++; } return; } if (kCount.size() == cap) { auto [k,v] = countKV[minCount][0]; int count = kCount[k]; auto it = kv[k]; countKV[count].erase(it); kv.erase(k); kCount.erase(k); } minCount = 1; countKV[minCount].insert({key,value}); kv[key] = countKV[minCount][countKV[minCount].size() - 1]; // need iter kCount[key] = minCount; } private: int cap; int minCount; unordered_map<int, vector<pair<int,int>>> countKV; unordered_map<int, vector<pair<int,int>>::iterator> kv; unordered_map<int, int> kCount; };
Editor is loading...
Leave a Comment