146. LRU 缓存机制
1. 题解
1 class LRUCache { 2 public: 3 LRUCache(int capacity) { 4 cap = capacity; 5 } 6 7 int get(int key) { 8 9 auto it = m.find(key); 10 if(it == m.end()) return -1; 11 12 l.splice(l.begin(), l, it->second); 13 return it->second->second; 14 } 15 16 void put(int key, int value) { 17 auto iter = m.find(key); 18 if(iter != m.end()) l.erase(iter->second); 19 l.push_front(make_pair(key, value)); 20 m[key] = l.begin(); 21 22 if(m.size() > cap) 23 { 24 auto it = l.rbegin(); 25 m.erase(it->first); 26 27 l.pop_back(); 28 } 29 } 30 private: 31 int cap; 32 list<pair<int, int>> l; 33 unordered_map<int, list<pair<int,int>>::iterator> m; 34 }; 35 36 /** 37 * Your LRUCache object will be instantiated and called as such: 38 * LRUCache* obj = new LRUCache(capacity); 39 * int param_1 = obj->get(key); 40 * obj->put(key,value); 41 */