leetcode LRU Cache
2014-11-24 00:29
411 查看
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:
otherwise return -1.
cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
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.
class LRUCache{ private: list<pair<int,int> > keyList; unordered_map<int, list<pair<int,int> >::iterator> cacheTable; int capacity; void updateCache(int key,int value){ keyList.erase(cacheTable[key]); cacheTable[key] = keyList.insert(keyList.end(), make_pair(key,value)); } public: LRUCache(int capacity) { this->capacity = capacity; } int get(int key) { if(cacheTable.find(key) == cacheTable.end()){ return -1; }else{ updateCache(key, cacheTable[key]->second); return cacheTable[key]->second; } } void set(int key, int value) { if(cacheTable.find(key) != cacheTable.end()){ updateCache(key, value); }else{ if(capacity <= 0){ cacheTable.erase(keyList.front().first); keyList.pop_front(); }else{ capacity--; } cacheTable[key] = keyList.insert(keyList.end(), make_pair(key,value)); } } };
相关文章推荐
- LeetCode "LRU Cache"
- leetcode LRU Cache(高级缓存的最近最少使用算法实现)
- LeetCode-LRU Cache<未完成>
- [leetcode]LRU Cache @ Python
- 2015.03.28 leetcode LRU cache 解题记录
- LeetCode LRU Cache
- Leetcode LRU Cache
- leetcode_Design and implement a data structure for Least Recently Used (LRU) cache
- Leetcode LRU Cache
- LeetCode 之 LRU Cache Java实现
- LeetCode LRU Cache STL
- LeetCode——LRU Cache
- LeetCode LRU Cache
- LRU Cache leetcode
- leetcode :LRU Cache
- Leetcode LRU Cache
- leetcode LRU Cache(**)
- leetcode LRU Cache
- LeetCode (26) LRU Cache
- LeetCode LRU Cache