设计LRU缓存结构(C++,unordered_map+双向链表)

设计LRU缓存结构_牛客题霸_牛客网

推荐几篇大神文章:

LRU原理和Redis实现——一个今日头条的面试题 - 知乎

其实吧,LRU也就那么回事

class LRUchache {
	struct ListNode{
		ListNode* pre;
		ListNode* next;
		int key;
		int value;
		ListNode(int _key, int _value):
			pre(nullptr),
			next(nullptr),
			key(_key),
			value(_value)
		{}
	};
public:
	LRUchache(int capcity) :
		capcity(capcity),
		size(0) {
		pHead = new ListNode(-1, -1);
		pTail = new ListNode(-1, -1);
		pHead->next = pTail;
		pTail->pre = pHead;
	}
		
	void set(int key, int val) {
		unordered_map::iterator it = m.begin();
		it = m.find(key);
		if (it != m.end()) {
			it->second->value = val;
			//将其添加到链表首端
			it->second->next = pHead->next;
			pHead->next->pre = it->second;
			pHead->next = it->second;
			it->second->pre = pHead;
			++size;
		}
		else {
			ListNode* node = new ListNode(key, val);
			//判断当前容量值
			if (size == capcity) {
				//容量不足,删除最后一个
				int key = pTail->pre->pre->next->key;
				pTail->pre->pre->next = pTail;
				pTail->pre = pTail->pre->pre;
				m.erase(key);
				--size;
			}
			//添加到首部
			node->next = pHead->next;
			pHead->next->pre = node;
			pHead->next = node;
			node->pre = pHead;
			m[key] = node;
			++size;
		}
	}

	int get(int key) {
		int ret = 0;
		unordered_map::iterator it = m.begin();
		it = m.find(key);
		if (it != m.end()) {
			ret = it->second->value;
		}
		else {
			return -1;
		}
		//将其添加到链表首端
		it->second->next->pre = it->second->pre;
		it->second->pre->next = it->second->next;
		it->second->next = pHead->next;
		pHead->next->pre = it->second;
		pHead->next = it->second;
		it->second->pre = pHead;

		return ret;
	}
private:
	unordered_map m;
	ListNode* pHead;
	ListNode* pTail;
	int capcity;
	int size;
};

vector LRU(vector >& operators, int k) {
	LRUchache lru(k);
	vector v;
	for (size_t i = 0; i < operators.size(); ++i) {
		if (operators[i][0] == 1) {
			lru.set(operators[i][1], operators[i][2]);
		}
		else if(operators[i][0] == 2){
			v.push_back(lru.get(operators[i][1]));
		}
	}
	return v;
}

你可能感兴趣的:(缓存,链表,散列表)