编程实现一个LRU算法

这一题要我们设计一个LRU(最近最少使用算法),我的思路是用一个hash表加一个双向链表实现,其插入,删除,获取节点时间复杂度均在O(1),代码如下

class LRUCache {
public:
	struct node {
		int key;
		int val;
		node* front;
		node* next;
		node() : val(0), front(NULL), next(NULL) {};
		node(int value, int Key) :val(value), key(Key), front(NULL), next(NULL) {};
	};
	LRUCache(int capacity) {
		maxsize = capacity;
		head = new node();
		tail = new node();
		head->next = tail;
		tail->front = head;
	}

	int get(int key) {
		if (!m.count(key) || maxsize == 0) return -1;
		node& n = m[key];
		visied(n);
		return n.val;
	}

	void put(int key, int value) {
		if (maxsize == 0)  return;
		m[key].val = value;
		m[key].key = key;
		visied(m[key]);
		if (m.size()>maxsize)
			pop();
	}
	void visied(node& n) {
		if (n.front)
			n.front->next = n.next;
		if (n.next)
			n.next->front = n.front;
		n.next = head->next;
		head->next->front = &n;
		head->next = &n;
		n.front = head;
	}
	void pop() {
		node* temp = tail->front;
		tail->front = temp->front;
		temp->front->next = tail;
		m.erase(temp->key);
	}
private:
	int size;
	int maxsize;
	node* head;
	node* tail;
	unordered_map<int, node> m;
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值