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

      

  • 相关阅读:
    友链
    P2572 [SCOI2010]序列操作
    「THP3考前信心赛」解题报告
    DP中的树上边/点覆盖问题
    P3413 SAC#1
    luoguP6754 [BalticOI 2013 Day1] Palindrome-Free Numbers
    睿智错误
    常见套路?
    奇怪的点子
    最近做过一些比较好的题
  • 原文地址:https://www.cnblogs.com/zeze/p/9590107.html
Copyright © 2011-2022 走看看