LRU

设计和构建一个“最近最少使用”缓存,该缓存会删除最近最少使用的项目。缓存应该从键映射到值(允许你插入和检索特定键对应的值),并在初始化时指定最大容量。当缓存被填满时,它应该删除最近最少使用的项目。

它应该支持以下操作: 获取数据 get 和 写入数据 put 。

获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,从而为新的数据值留出空间。

示例:

LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // 返回  1
cache.put(3, 3);    // 该操作会使得密钥 2 作废
cache.get(2);       // 返回 -1 (未找到)
cache.put(4, 4);    // 该操作会使得密钥 1 作废
cache.get(1);       // 返回 -1 (未找到)
cache.get(3);       // 返回  3
cache.get(4);       // 返回  4



HashMap 容器中底层是一个 Node 数组

class LRUCache {
    private Map<Integer,ListNode> map = new HashMap<>();
    private int capacity;
    private ListNode head,tail;
    public LRUCache(int capacity) {
        this.capacity=capacity;
        head = new ListNode(0,0);
        tail = new ListNode(0,0);
        head.next = tail;
        tail.pre = head;
    }
    
    public int get(int key) {
        if(!map.containsKey(key))
            return -1;
        ListNode tempNode=map.get(key);
        moveToHead(tempNode);
        return tempNode.getVal();
    }
    
    public void put(int key, int value) {
        if(map.containsKey(key)){
            ListNode tempNode = map.get(key);
            tempNode.setVal(value);
            moveToHead(tempNode);
        }else{
            if(capacity==0){
                deleteTail();
                
            }
            ListNode node = new ListNode(key,value);
            map.put(key,node);
            addToHead(node);
            if(capacity>0)
                capacity--;
        }
    }

    void addToHead(ListNode node){
        head.next.pre = node;
        node.next = head.next;
        head.next = node;
        node.pre =  head;
    }

    void moveToHead(ListNode tempNode){
        tempNode.pre.next=tempNode.next;
        tempNode.next.pre=tempNode.pre;
        head.next.pre=tempNode;
        tempNode.next=head.next;
        head.next=tempNode;
        tempNode.pre=head;
    }

    void deleteTail(){
        ListNode node = tail.pre;
        node.pre.next=tail;
        tail.pre=node.pre;
        map.remove(node.key);
    }
}

class ListNode{
    int key;
    int val;
    ListNode pre;
    ListNode next;
    ListNode(int key,int val){
        this.key=key;
        this.val=val;
    }
    int getVal(){
        return this.val;
    }
    void setVal(int val){
        this.val=val;
    }
}

 

posted @ 2020-08-20 10:43  你眼里的星辰  阅读(201)  评论(0)    收藏  举报