LRU缓存淘汰算法 双向链表+哈希map

LeetCode146题

思路

1.双向链表方便删除操作
2.最近使用的资源更新到表头,表尾自然就是长时间未被使用的资源
3.资源不够的时候删除表尾

代码

#include <iostream>
#include<unordered_map>
using namespace std;
class Node {
public:
	int key;
	int value;
	Node* next;
	Node* pre;
	Node(int mkey = 0, int mvalue = 0) :key(mkey), value(mvalue), next(nullptr), pre(nullptr) {};
};

class DoubleList
{
private:
	Node* head;
	Node* tail;
	int Size;
public:
	DoubleList() :Size(0)
	{
		head = new Node;
		tail = new Node;
		head->next = tail;
		tail->pre = head;

	}
	//头部插入
	void push_front(Node* node)
	{
		node->next = head->next;
		head->next->pre = node;
		head->next = node;
		node->pre = head;
		Size++;
	}
	//删除节点
	void remove(Node* node)
	{
		if (Size == 0)
			return;
		node->pre->next = node->next;
		node->next->pre = node->pre;
		Size--;
	}
	//删除尾部节点
	Node* pop_tail()
	{
		if (Size == 0)
			return nullptr;
		Node* temp = tail->pre;	//尾部节点
		temp->pre->next = tail;
		tail->pre = temp->pre;
		Size--;
		return temp;
	}
};

class LRUCache {
public:
	int maxCap;
	DoubleList list;
	unordered_map<int, Node*> mp;
	int curSize;
	LRUCache(int capacity) {
		maxCap = capacity;
		curSize = 0;
	}

	int get(int key) {
		if (mp.count(key))
		{
			Node* temp = mp[key];
			//更新链表中位置
			list.remove(temp);
			list.push_front(temp);
			return mp[key]->value;
		}
		return -1;
	}

	void put(int key, int value) {
		if (mp.count(key))
		{
			mp[key]->value = value;
			Node* temp = mp[key];
			//节点从原来位置断开
			list.remove(temp);
			list.push_front(temp);
			return;
		}
		Node* newNode = new Node{ key,value };
		if (curSize == maxCap)
		{
			//清除最长时间未用的资源
			Node* temp = list.pop_tail();
			mp.erase(temp->key);
			curSize--;
			delete temp;
		}
		list.push_front(newNode);
		mp[key] = newNode;
		curSize++;
	}
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */
int main()
{
	LRUCache* obj = new LRUCache(2);
	obj->put(2, 1);
	obj->put(1, 1);
	obj->put(2, 3);
	obj->put(4, 1);
	obj->get(1);
	obj->get(2);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值