intget(int key){ if (capacity == 0) return-1; auto it = hash.find(key); if (it == hash.end()) return-1; list<Node>::iterator node = it -> second; int val = node -> val; key_list.erase(node); insert(key, val); return val; } voidput(int key, int value){ if (capacity == 0) return; if (get(key) != -1) { hash[key] -> val = value; return; } if (hash.size() < capacity) { insert(key, value); } else { int remove_key = key_list.front().key; key_list.pop_front(); hash.erase(remove_key); insert(key, value); } }
private: int capacity; list<Node> key_list; unordered_map<int, list<Node>::iterator> hash; };
/** * 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); */
LFU 缓存
主要考虑数据结构的选用。哈希表 key_table 存储 key 与 值信息与它在链表中的位置 的映射,如果没有 freq 的要求(即简单的 LRU),只需要维护一个 list 即可,可以解决时间先后问题。但是考虑到有 freq 的要求,这里就可以对 list 进行拆分,可以用一个哈希表来存储 freq 与 list 的映射 freq_table。这样就可以首先解决 freq 问题,同时根据 list 解决 LRU 最近最久未使用问题。
/** * 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); */