码迷,mamicode.com
首页 > 系统相关 > 详细

Leetcode- LRUCache

时间:2014-10-18 12:37:51      阅读:328      评论:0      收藏:0      [点我收藏+]

标签:blog   io   java   2014   on   log   ad   时间   new   

关键是搞懂题目(不知道LRUCache的只能自己google了)。

然后用双向链表来模拟cache被get和set。但是naive implementation会exceed time limit。所以最大的关键是用一个HashMap来记录key在链表中的位置,这样子每次查询是O(1)的时间,否则O(n)。

这个也是很经典的用Map来加速双向链表查询的思路(前提是key要唯一)。


import java.util.*;

public class LRUCache {

	Map<Integer, DoubleLinkedListNode> hmap = new HashMap<Integer, DoubleLinkedListNode>();
	DoubleLinkedListNode head = null;
	DoubleLinkedListNode tail = null;
	int capa;

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

	public int get(int key) {

		if (hmap.containsKey(key)) {
			DoubleLinkedListNode tnode = hmap.get(key);
			tnode = removeNode(tnode);
			pushFront(tnode);
			return tnode.value;
		}
		return -1;
	}

	public void set(int key, int value) {

		if (hmap.containsKey(key) == true) {

			DoubleLinkedListNode tnode = hmap.get(key);
			tnode.value = value;
			tnode = removeNode(tnode);

			pushFront(tnode);
		}

		else {
			DoubleLinkedListNode newNode = new DoubleLinkedListNode(key,value);

			if (hmap.size() == capa) {
				hmap.remove(tail.key);
				removeNode(tail);
			}

			pushFront(newNode);
			hmap.put(key, newNode);
		}
	}

	void pushFront(DoubleLinkedListNode node) {
		if (head == null) {
			head = tail = node;
		} else {
			node.next = head;
			head.prev = node;
			head = node;
		}
		return;
	}

	DoubleLinkedListNode removeNode(DoubleLinkedListNode node) {
		DoubleLinkedListNode prev = node.prev;
		DoubleLinkedListNode next = node.next;

		if (prev != null) {
			prev.next = next;
		} else {
			head = next;
		}

		if (next != null) {
			next.prev = prev;
		} else {
			tail = prev;
		}

		node.prev = null;
		node.next = null;

		return node;
	}

	class DoubleLinkedListNode {
		int key;
		int value;
		DoubleLinkedListNode prev;
		DoubleLinkedListNode next;

		public DoubleLinkedListNode(int key, int val) {
			this.key = key;
			this.value = val;
			prev = null;
			next = null;
		}

		public DoubleLinkedListNode() {
			value = 0;
			prev = null;
			next = null;
		}
	}
	

}


Leetcode- LRUCache

标签:blog   io   java   2014   on   log   ad   时间   new   

原文地址:http://blog.csdn.net/tspatial_thunder/article/details/40210265

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!