1. 程式人生 > >LeetCode 146. LRU Cache

LeetCode 146. LRU Cache

高頻題,需要用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<pair<int,int>> l; // pair(key,val)
    unordered_map<int,list<pair<int
,int>>::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); */