編程實現一個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;
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章