zoukankan      html  css  js  c++  java
  • 【LeetCode】LRU Cache

    设计和实现一个  LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 

    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;
    	}
    }
    

      

  • 相关阅读:
    剑指Offer
    剑指Offer
    剑指Offer
    选书
    马的遍历
    从事效应
    魔性的素数环1~20 自带解释~
    [POJ1236]Network of Schools(并查集+floyd,伪强连通分量)
    [HDOJ3974]Assign the task(建树胡搞)
    [HDOJ4027]Can you answer these queries?(线段树,特殊成段更新,成段查询)
  • 原文地址:https://www.cnblogs.com/zeze/p/9590107.html
Copyright © 2011-2022 走看看