leetcode 146. LRU Cache
2015-01-17 16:25
267 查看
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:
为了查找高效O(1),考虑使用哈希表hash, 为了使插入/删除高效O(1),考虑使用双链表list, 因此采用双链表和哈希表结合。
GET(key):
hash命中节点node,把node从list中移动到表头,否则返回-1
SET(key, value):
hash命中node,只需更新hash中的node,并把node从list中移动到表头。
hash不命中,则需要判断capacity. 如果cache满,需要替换cache中的node,并删除list的表尾元素,cache未满,将node插入表头,更新cache。
getand
set.
get(key)- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value)- Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
为了查找高效O(1),考虑使用哈希表hash, 为了使插入/删除高效O(1),考虑使用双链表list, 因此采用双链表和哈希表结合。
GET(key):
hash命中节点node,把node从list中移动到表头,否则返回-1
SET(key, value):
hash命中node,只需更新hash中的node,并把node从list中移动到表头。
hash不命中,则需要判断capacity. 如果cache满,需要替换cache中的node,并删除list的表尾元素,cache未满,将node插入表头,更新cache。
struct CacheNode { int key; int value; CacheNode(int k, int v):key(k), value(v){} }; class LRUCache{ public: LRUCache(int capacity) { cacheSize = capacity; } int get(int key) { if (cacheMap.find(key) == cacheMap.end()) // hit fail return -1; cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]); cacheMap[key] = cacheList.begin(); return cacheMap[key]->value; } void set(int key, int value) { if (cacheMap.find(key) == cacheMap.end()) // hit fail { CacheNode cacheItem(key, value); if (cacheMap.size() == cacheSize) // cache is full { cacheMap.erase(cacheList.back().key); cacheList.pop_back(); } cacheList.push_front(cacheItem); cacheMap[key] = cacheList.begin(); } else // hit success { cacheMap[key]->value = value; cacheList.splice(cacheList.begin(), cacheList, cacheMap[key]); cacheMap[key] = cacheList.begin(); } } private: int cacheSize; unordered_map<int, list<CacheNode>::iterator> cacheMap; list<CacheNode> cacheList; };
相关文章推荐
- [LeetCode]146. LRU Cache
- [leetcode] 146. LRU Cache
- LeetCode 146. LRU Cache
- Leetcode 146. LRU Cache
- leetcode No146. LRU Cache
- leetcode 146. LRU Cache
- [leetcode] 146. LRU Cache
- [LeetCode] 146. LRU Cache
- 146. LRU Cache
- 146. LRU Cache
- Leetcode LRU Cache
- leetcode LRU cache
- LeetCode LRU Cache
- 146. LRU Cache
- LeetCode LRU Cache
- Leetcode之LRU Cache
- **Leetcode_lru-cache (c++ version)
- leetcode LRU Cache
- Leetcode LRU Cache 解题报告
- leetcode LRU Cache python