高频题,需要用unordered_map和list,做到O(1)
需要注意的一点是,list用了splice改变了节点的位置,但是iterator并不会失效,这也代表unordered_map不需要进行更新。(可以把iterator当成指针方便理解)
class LRUCache {public: int cap; // recent visit will be moved to the head list> l; // pair(key,val) unordered_map >::iterator> m; // key -> iterator in list LRUCache(int capacity) { cap = capacity; } int get(int key) { if (!m.count(key)) return -1; int res=(*m[key]).second; l.splice(l.begin(), l, m[key]); //move key to the first return res; } void put(int key, int value) { if (m.count(key)) l.erase(m[key]); l.push_front(make_pair(key,value)); m[key] = l.begin(); if (l.size()>cap){ m.erase(l.back().first); l.pop_back(); } }};/** * 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); */