其他分享
首页 > 其他分享> > LRU缓存机制

LRU缓存机制

作者:互联网

题目链接

LRU缓存机制

题目描述

注意点

解答思路

代码

class LRUCache {
    class DLinkedNode {
        int key;
        int value;
        DLinkedNode prev;
        DLinkedNode next;
        public DLinkedNode() {}
        public DLinkedNode(int key, int value) {this.key = key; this.value = value;}
    }

    //用于存储键值对
    Map<Integer,DLinkedNode> map = new HashMap<>();
    //空间大小
    int capacity = 0;
    int size = 0;
    //虚拟头结点和尾结点,方便后续删除和添加结点
    DLinkedNode head;
    DLinkedNode tail;

    //初始化
    public LRUCache(int capacity) {
        this.capacity = capacity;
        head = new DLinkedNode();
        tail = new DLinkedNode();
        head.next = tail;
        tail.prev = head;
    }
    
    public int get(int key) {
        if(map.get(key) == null){
            return -1;
        }else{
            if(map.get(key) != head.next){
                //能找到该结点,则需要将该结点放到头部
                moveToHead(map.get(key));
            }
            return map.get(key).value;
        }
    }
    
    public void put(int key, int value) {
        //将该结点添加进DLinkedNode中
        //map中是否已经有该key值
        if(map.get(key) != null){
            DLinkedNode node = map.get(key);
            node.value = value;
            moveToHead(node);
        }else{
            //判断是否超出容量
            if(size == capacity){
                //超出容量的情况
                //先删除最后一个结点
                delTail();
                DLinkedNode node = new DLinkedNode(key,value);
                map.put(key,node);
                //将该结点设置为头结点
                setHead(node);
            }else{
                //没有超出容量,直接将该结点添加进map中,并设置为头结点
                DLinkedNode node = new DLinkedNode(key,value);
                map.put(key,node);
                setHead(node);
                size++;
            }
        }
        
    }

    //将双链表中的某个结点设置为头结点
    public void moveToHead(DLinkedNode node){
        node.prev.next = node.next;
        node.next.prev = node.prev;
        setHead(node);
    }

    //设置头结点
    public void setHead(DLinkedNode node){
        DLinkedNode nex = head.next;
        head.next = node;
        node.prev = head;
        nex.prev = node;
        node.next = nex;
    }

    //删除尾结点
    public void delTail(){
        //从map中删除
        map.remove(tail.prev.key);
        tail.prev = tail.prev.prev;
        tail.prev.next = tail;
    }
}

/**
 * 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);
 */

/**
 * 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);
 */

关键点

标签:node,map,结点,缓存,int,DLinkedNode,LRU,key,机制
来源: https://blog.csdn.net/weixin_51628158/article/details/118888751