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

146. LRU Cache

时间:2017-10-17 09:54:04      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:node   pac   get   rem   val   sharp   add   log   blog   

class LRUCache {
    class DNode{
        public int val;
        public int key;
        public DNode pre;
        public DNode next;
        public DNode(int k, int v){
            key=k;
            val=v;
        }
    }
    private Map<Integer, DNode> map=new HashMap<Integer, DNode>();
    private DNode head=new DNode(0,0);
    private DNode tail=new DNode(0,0);
    private int cap=0;
    private int cur=0;
    private void add(DNode node){
        node.pre=head;
        node.next=head.next;
        node.pre.next=node;
        node.next.pre=node;
    }
    private void remove(DNode node){
        node.pre.next=node.next;
        node.next.pre=node.pre;
    }
    private void move(DNode node){
        remove(node);
        add(node);
    }
    public LRUCache(int capacity) {
        cap=capacity;
        cur=0;
        head.next=tail;
        tail.next=head;
    }
    public int get(int key) {
        if(!map.containsKey(key))
            return -1;
        DNode node=map.get(key);
        move(node);
        return node.val;
    }
    
    public void put(int key, int value) {
        if(map.containsKey(key))
        {
            DNode node=map.get(key);
            node.val=value;
            move(node);
        }
        else
        {
            DNode node=new DNode(key,value);
            add(node);
            map.put(key,node);
            if(cur<cap)
                cur++;
            else
            {
                DNode last=tail.pre;
                remove(last);
                map.remove(last.key);
            }
        }
    }
}

  

146. LRU Cache

标签:node   pac   get   rem   val   sharp   add   log   blog   

原文地址:http://www.cnblogs.com/asuran/p/7679749.html

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