赞
踩
基本思想是借助hash_map实现链表的快速查找,同时快速添加删除子节点。
C++
实现class LRUCache { public: LRUCache(int capacity) : cap(capacity) { } int get(int key) { if (map.find(key) == map.end()) return -1; auto key_value = *map[key]; cache.erase(map[key]); cache.push_front(key_value); map[key] = cache.begin(); return key_value.second; } void put(int key, int value) { if (map.find(key) == map.end()) { if (cache.size() == cap) { map.erase(cache.back().first); cache.pop_back(); } } else { cache.erase(map[key]); } cache.push_front({key, value}); map[key] = cache.begin(); } private: int cap; list<pair<int, int>> cache; unordered_map<int, list<pair<int, int>>::iterator> map; };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。