#146 LRU cache

class LRUCache {
private:
	std::unordered_map<int, int> mapData;
	std::unordered_map<int, std::list<int>::iterator> mapIndex;
	std::list<int> list;
	int maxSize;
public:
	LRUCache(int capacity) {
		maxSize = capacity;
	}

	int get(int key) {
		auto search = mapData.find(key);

		if (search != mapData.end()) {//find it
			auto pair_delete = mapIndex.find(key);
			list.erase(pair_delete->second);

            list.push_back(key);			
            pair_delete->second = std::prev(list.end());
			return search->second;
		}
		else {//not find
			return -1;
		}
	}

	void put(int key, int value) {
		auto search = mapData.find(key);
		if (search != mapData.end()) {//find it
			auto pair_delete = mapIndex.find(key);
			list.erase(pair_delete->second);

            list.push_back(key);
            pair_delete->second = std::prev(list.end());	
			search->second = value;

		}
		else {//not find
			  //push to list
			list.push_back(key);
			mapData[key] = value;
			mapIndex[key] = std::prev(list.end());

			//overflow
			this->removeLRU();
		}
	}
	void removeLRU() {
		if (list.size() > maxSize) {
			auto iterBegin = list.begin();
			mapData.erase(*iterBegin);
			mapIndex.erase(*iterBegin);
			list.pop_front();
		}

	}
};

  

原文地址:https://www.cnblogs.com/dongfangchun/p/7724736.html