【常数时间】LRU(Least Recently Used)最近最少使用算法设计C++实现

#include
#include
#include
#include
#include
#include
using namespace std;

class LRUCache {
public:
	LRUCache(int capacity) {
		cap = capacity;
	}

	int get(int key) {	
		// 获得键值对的值,并将其调至链表头,同时更新map中的映射
		auto it = map.find(key);
		if (it == map.end())
			return -1;
		else {
			int val = it->second->second;
			// 更新链表
			cache.push_front(pair<int, int>(key, val));
			cache.erase(it->second);
			// 更新map的映射
			it = map.find(key);
			// 新的迭代器指向链表头
			it->second = cache.begin();
			return val;
		}

	}

	void put(int key, int value) {
		auto it = map.find(key);
		if (it == map.end()) {	//需要插入操作
			cache.push_front(pair<int, int>(key, value));
			map[key] = cache.begin();	//更新哈希表
			if (map.size() > cap) {	//超出容纳限额,则弹出最后的键值对,并删除表中的映射
				map.erase(map.find(cache.back().first));
				cache.pop_back();
			}
		}
		else {	//表中已有该键值对,更新map的映射,并且将其在链表中提前
			cache.push_front(pair<int, int>(key, value));
			cache.erase(it->second);
			it = map.find(key);
			it->second = cache.begin();
		}
	}
private:
	int cap;
	list<pair<int, int>> cache;	//双链表,装着(key,value)元组
	unordered_map<int, list<pair<int, int>>::iterator> map;
};

你可能感兴趣的:(算法)