146. LRU 缓存

力扣链接:. - 力扣(LeetCode)

思路:双向链表用来维护"最近最少使用",hashmap用来比较方便的根据key取value

java 复制代码
class LRUCache {
    class Node{
        Node pre;
        Node next;
        int key, val;
        Node(){}
        Node(int key, int val){
            this.key = key;
            this.val = val;
        }
    }
    private int capacity;
    private Map<Integer, Node> cache;
    //分别指向头尾节点,便于在头部插入和在尾部删除节点
    private Node head, tail;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.cache = new HashMap<>();
        head = new Node();
        tail = new Node();
        head.next = tail;
        tail.pre = head;
    }
    
    public int get(int key) {
        Node node = cache.get(key);
        if(node == null) return -1;
        //如果存在,则移到头部
        moveToHead(node);
        return node.val;
    }
    
    public void put(int key, int value) {
        Node node = cache.get(key);
        if(node != null) {
            node.val = value;
            moveToHead(node);
        } else {
            Node newNode = new Node(key, value);
            //如果容量超了,先移除
            if(cache.size()==capacity){
                Node realTail = tail.pre;
                removeNode(realTail);
                cache.remove(realTail.key);
            }
            addHead(newNode);
            cache.put(key, newNode);
        }
    }

    private void moveToHead(Node node) {
        removeNode(node);
        addHead(node);
    }

    private void removeNode(Node node) {
        Node nextNode = node.next;
        Node preNode = node.pre;
        preNode.next = nextNode;
        nextNode.pre = preNode;
    }

    private void addHead(Node node) {
        node.next = head.next;
        head.next.pre = node;
        node.pre = head;
        head.next = node;
    }
}
相关推荐
工一木子4 小时前
URL时间戳参数深度解析:缓存破坏与前端优化的前世今生
前端·缓存
陌殇殇4 小时前
SpringBoot整合SpringCache缓存
spring boot·redis·缓存
数据狐(DataFox)11 小时前
SQL参数化查询:防注入与计划缓存的双重优势
数据库·sql·缓存
大只鹅12 小时前
Springboot3整合ehcache3缓存--XML配置和编程式配置
spring boot·缓存
持之以恒的天秤13 小时前
Redis—哨兵模式
redis·缓存
西岭千秋雪_15 小时前
Redis缓存架构实战
java·redis·笔记·学习·缓存·架构
大只鹅18 小时前
两级缓存 Caffeine + Redis 架构:原理、实现与实践
redis·缓存·架构
zzywxc78719 小时前
如何高效清理C盘、释放存储空间,让电脑不再卡顿。
经验分享·缓存·性能优化·电脑
UQI-LIUWJ21 小时前
计算机组成笔记:缓存替换算法
笔记·缓存
harmful_sheep1 天前
Spring 为何需要三级缓存解决循环依赖,而不是二级缓存
java·spring·缓存