classLRUCache { public: LRUCache(int capacity) { cap = capacity; } intget(int key){ auto it = m.find(key); if(it == m.end()) return-1; // 刚访问过的结点移动到链表头 lst.splice(lst.begin(), lst, it->second); return m[key]->second; } voidput(int key, int value){ auto it = m.find(key); // key已经存在,抹去 if(it != m.end()) lst.erase(it->second); // 插入链表头 lst.push_front(make_pair(key, value)); // 建立key到list迭代器的映射 m[key] = lst.begin(); // 元素个数超过缓存容量大小 if(m.size() > cap) { int k = lst.rbegin()->first; // 删除链表末尾(最近最少使用)元素 lst.pop_back(); m.erase(k); } } private: // 缓存容量 int cap; // 链表,元素为(key,value)对 list<pair<int, int> > lst; // 哈希表,key-->(key,value)迭代器 unordered_map<int, list<pair<int, int> >::iterator> m; };
/** * 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); */
/** * Your LFUCache object will be instantiated and called as such: * LFUCache* obj = new LFUCache(capacity); * int param_1 = obj->get(key); * obj->put(key,value); */