146. LRU缓存机制

心得:难度在于操作要用O(1)的时间复杂度,构造双端列表

重点在,要加一个头节点和尾节点,可以简化操作。然后进行操作

代码:

class ListNode {
    int val;
    int key;
     ListNode next;
     ListNode pro;
    ListNode(int key,int value) 
    { 
        this.key=key;
        this.val=value;
    }
 }
class MList
{

    ListNode head=new ListNode(-1,-1);
    ListNode tail=new ListNode(-1,-1);
    MList()
    {
        head.next=tail;
        tail.pro=head;
    }
    public void addFirst(ListNode node)
    {
        
            node.next=head.next;
            head.next.pro=node;
            head.next=node;
            node.pro=head;
    }
    public void removeNode(ListNode node)
    {
       node.pro.next=node.next;
       node.next.pro=node.pro;
    }
    public ListNode removeLast()
    {
        ListNode node=tail.pro;
        this.removeNode(node);
        return node;
    }
}
class LRUCache {
HashMap<Integer,ListNode> map=new HashMap<>();
    MList list=new MList();
    int capcity=0;
      LRUCache(int capcity) {
          this.capcity=capcity;
        }
        
        public int get(int key) {
            if(map.containsKey(key))
            {
                list.removeNode(map.get(key));
                list.addFirst(map.get(key));
                return map.get(key).val;
            }
            else
                return -1;
        }
        
        public void put(int key, int value) {
            if(map.containsKey(key))
            {
                ListNode node=map.get(key);
                node.val=value;
                list.removeNode(map.get(key));
                list.addFirst(map.get(key));
            }
            else
            {
                ListNode node=new ListNode(key,value);
                if(map.size()==capcity)
                {
                    ListNode tmp=list.removeLast();
                    map.remove(tmp.key);
                    list.addFirst(node);
                    map.put(key, node);
                }
                else
                {
                    list.addFirst(node);
                    map.put(key, node);
                }
            }
        }

}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */

 

posted @ 2019-07-20 22:52  pc_m  阅读(381)  评论(0编辑  收藏  举报