[哈希] leetcode 146 LRU Cache
problem : https://leetcode.com/problems/lru-cache/
这道题的想法是维护三个数组,一个data记录实际的key-value数据,一个LRU的list记录LRU数据,一个pos记录每个数字所在的链表的位置。
对于LRU而言,每次访问到了出现过的数字,我们需要快速地将原有数字移到末尾处。因此可以想到能够使用list来实现快速删除、插入的操作。
为了快速定位对应数字的位置,我们可以用一个哈希来维护数字和它对应在链表中的位置。最终算法复杂度为O(1)。
class LRUCache { public: int size; unordered_map<int,int> data; unordered_map<int,list<int>::iterator> pos; list<int> LRUList; LRUCache(int capacity) { size = capacity; } int get(int key) { if(data.find(key) == data.end()) { return -1; } update(key); return data[key]; } void update(int key) { LRUList.push_back(key); if(pos.find(key) != pos.end()) { LRUList.erase(pos[key]); } auto t = LRUList.end(); t--; pos[key] = t; // for(auto d : LRUList) cout << d <<" "; cout <<endl; } void put(int key, int value) { if(data.size() == size) { if(!pos.empty() && pos.find(key) == pos.end()) { int remove_key = LRUList.front(); data.erase(remove_key); pos.erase(remove_key); LRUList.pop_front(); } } update(key); data[key] = value; } }; /** * Your LRUCache object will be instantiated and called as such: * LRUCache* obj = new LRUCache(capacity); * int param_1 = obj->get(key); * obj->put(key,value); */

浙公网安备 33010602011771号