标签:des style class blog code color
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get
and 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.
LRU是近期最少使用算法,其一个例子为:
set(key, value)
,class LRUCache{ public: typedef pair<int,int> CacheItem; typedef list<CacheIterm>::iterator CacheItemIterator; typedef unordered_map<int,list<CacheItem>::iterator > CacheMap; typedef CacheMap::iterator CacheMapIterator; LRUCache(int capacity){ m_capacity = capacity; } int get(int key){ if(m_map.find(key) == m_map.end()) return -1; else{ moveToFirst(key); return m_map[key]->second; } } void set(int key, int value){ if(m_map.find(key) == m_map.end()){ if(m_cache.size() >= m_capacity){ m_map.erase(m_cache.back().first); m_cache.pop_back(); } m_cache.push_front(CacheItem(key,value)); m_map[key]=m_cache.begin(); }else{ m_map[key]->second = value; moveToFirst(key); } } void moveToFirst(int key){ CacheItemIterator itemIter = cacheMap[key]; m_cache.erase(itemIter); m_cache.push_front(*itemIter); m_map[key] = m_cache.begin(); } private: int m_capacity; CacheMap m_map; list<CacheItem> m_cache; };
Leetcode LRU Cache,布布扣,bubuko.com
标签:des style class blog code color
原文地址:http://www.cnblogs.com/xiongqiangcs/p/3795003.html