146. LRU Cache

Posted 鸵鸟

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了146. LRU Cache相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

leetcode@ [146] LRU Cache (TreeMap)

146. LRU Cache

146. LRU Cache

leetcode146 LRU Cache

146. LRU Cache

146 LRU Cache