`
huntfor
  • 浏览: 201201 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

[leetcode]LRU Cache

 
阅读更多

LRU Cache

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

 对LRU不了解的可以戳这里(感谢大神),这里需要自己手动建立一个双向链表,然后加上HashMap的协助从而达到O(1)时间的定位,双向链表能帮助我们达到删除节点,插入节点O(1)时间复杂度。具体的实现并不是很复杂。算法大家不明白戳这里,java代码如下:

首先自己定义一个双向链表:

class Node{
	private int key;
	private int value;
	private Node pre;
	private Node next;
	{
		pre = null;
		next = null;		
	}
	public Node(){
		this.key = Integer.MIN_VALUE;
		this.value = Integer.MIN_VALUE;
	}
	public Node(int key,int value){
		this.key = key;
		this.value = value;
	}
	public int getKey(){
		return key;
	}
	public int getValue(){
		return value;
	}
	public void setKey(int key){
		this.key = key;
	}
	public void setValue(int value){
		this.value = value;
	}
	public Node getPre(){
		return pre;
	}
	public void setPre(Node pre){
		this.pre = pre;
	}
	public Node getNext(){
		return next;
	}
	public void setNext(Node next){
		this.next = next;
	}
}

 

 

程序代码如下:

public class LRUCache {
	Map<Integer, Node> map = new HashMap<Integer, Node>();
	int capacity = 0;
	Node head = new Node();
	Node tail = new Node();
	
	public LRUCache(int capacity) {
		this.capacity = capacity ;
		head.next = tail;
		tail.pre = head;
	}
	public int get(int key) {
		if(map.containsKey(key)){
			Node e = map.get(key);
			delete(e);
			insert(tail, e);
			return e.getValue();
		}
		return -1;
	}
	public void set(int key, int value) {
		Node e = new Node(key,value);
		if(!map.containsKey(key)){
			if(map.size() < capacity){
				map.put(key, e);
				insert(tail, e);
			}else if(map.size() == capacity){
				map.remove(head.next.getKey());
				delete(head.next);
				insert(tail,e);
				map.put(key, e);
			}
		}else{
			Node exist = map.get(key);
			//remove node
			delete(exist);
			insert(tail,e);
			map.remove(key);
			map.put(key, e);
		}
	}
	private void delete(Node e){
		Node pre = e.pre;
		Node post = e.next;
		pre.next = post;
		post.pre = pre;
	}
	private void insert(Node tail,Node e){
		e.pre = tail.pre;
		e.next = tail;
		tail.pre.next = e;
		tail.pre = e;
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics