【LeetCode】LRU Cache

設計和實現一個  LRU (最近最少使用) 緩存機制。它應該支持如下操做: 獲取數據 get 和 寫入數據 put java

package letcode;

import java.util.HashMap;
import java.util.Map;

/**
 * 雙向鏈表+HashMap
 * 
 * @author zeze
 *
 */
public class LRUCache {
	
	
	public static void main(String[] args) {

		/*char key = 0;
		int value = 0;
		LRUCache obj = new LRUCache(capacity);
		int param_1 = obj.get(key);
		obj.put(key, value);*/

	}

	int capacity;
	Map<Integer, Node> map = new HashMap<Integer, Node>();
	Node head = null;
	Node end = null;



	public LRUCache(int capacity) {
		this.capacity = capacity;
	}

	public int get(int key) {

		if (map.containsKey(key)) {
			Node temp = map.get(key);
			remove(temp);// 移除節點
			setHead(temp);// 將節點設置爲頭結點
			return temp.value;
		}
		return -1;
	}
	
	public void put(int key, int value) {
		if (map.containsKey(key)) {// 更新節點
			Node old = map.get(key);
			old.value = value;
			remove(old);
			setHead(old);
		} else {// 插入節點
			Node created = new Node(key, value);
			if (map.size() >= capacity) {
				map.remove(end.key);// HashMap中移除尾節點
				remove(end);// 鏈表中移除尾節點
				setHead(created);
			} else {
				setHead(created);
			}
			map.put(key, created);
		}
	}

	private void setHead(Node n) {
		n.next = head;
		n.pre = null;
		if (head != null) {
			head.pre = n;
		}
		head = n;
		if (end == null)
			end = head;

	}

	private void remove(Node n) {
		if (n.pre != null)
			n.pre.next = n.next;
		else
			head = n.next;
		if (n.next != null)
			n.next.pre = n.pre;
		else
			end = n.pre;

	}

	
}

class Node {
	int key;
	int value;
	Node pre;
	Node next;

	Node(int key, int value) {
		this.key = key;
		this.value = value;
	}
}
相關文章
相關標籤/搜索