leetcode: LRU Cache
2014-06-30 12:32
337 查看
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:
the key if the key exists in the cache, otherwise return -1.
is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
网上找到的,自认为最优的解法,用一个unordered_map来保存key和对应list的迭代器,list保存key, value
要求对stl容器的成员函数很熟悉list.splice( iterator & pos, list, iterator &iter)
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.
网上找到的,自认为最优的解法,用一个unordered_map来保存key和对应list的迭代器,list保存key, value
要求对stl容器的成员函数很熟悉list.splice( iterator & pos, list, iterator &iter)
class LRUCache{ public: LRUCache(int capacity) { cap = capacity; } int get(int key) { if( cache.count( key)){ auto iter = cache[key]; cacheList.splice( cacheList.begin(), cacheList, iter); cache[key] = cacheList.begin(); return cacheList.begin()->value; } else return -1; } void set(int key, int value) { if( cache.count( key)){ auto iter = cache[key]; cacheList.splice( cacheList.begin(), cacheList, iter); cache[key] = cacheList.begin(); cacheList.begin()->value = value; } else{ if( cache.size() >= cap){ cache.erase( cacheList.back().key); cacheList.pop_back(); } cacheList.push_front( cacheNode( key, value)); cache[key] = cacheList.begin(); } } private: struct cacheNode{ int key; int value; cacheNode( int k, int v): key(k), value(v){} }; int cap; list< cacheNode> cacheList; unordered_map< int, list< cacheNode>::iterator> cache; };
相关文章推荐
- leetcode | LRU Cache
- [LeetCode][JavaScript]LRU Cache
- Leetcode: LRU Cache
- LeetCode -- LRU Cache
- LeetCode题目6:LRU Cache
- Leetcode: LRU Cache
- LeetCode - LRU Cache
- LeetCode: LRU Cache
- LeetCode: LRU Cache [146]
- 【Leetcode】 LRU Cache
- 【Leetcode146】LRU Cache
- [LeetCode]LRU Cache
- 【leetcode】LRU Cache(hard)★
- 【leetcode】LRU Cache
- [leetcode]LRU Cache
- LeetCode – LRU Cache (Java)
- Leetcode--LRU Cache
- LeetCode146—LRU Cache
- [LeetCode]146 LRU Cache
- LeetCode ---LRU Cache