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;
    }
}
相关推荐
snow@li1 小时前
数据库-Oracle:常用语法 / Oracle 核心知识技能梳理
数据库·redis·缓存
星辰_mya2 小时前
系统里的“特种部队”——缓存
缓存
snow@li2 小时前
数据库-Redis:常用语法 / Redis 核心知识技能梳理
数据库·redis·缓存
fuquxiaoguang3 小时前
金蝶天燕AMDC:当企业级缓存遇见Redis 8.2,国产中间件的“性能+易用”双飞跃
redis·缓存·中间件
AI木马人12 小时前
9.【AI任务队列实战】如何在高并发下保证系统不崩?(Redis + Celery完整方案)
数据库·人工智能·redis·神经网络·缓存
CyrusCJA21 小时前
在Windows系统上将Redis注册为系统服务使其实现开机自启
数据库·windows·redis·缓存
逆境不可逃1 天前
一篇速通Redis 从原理到Java实战(含缓存问题解决方案+集群配置)
数据库·redis·缓存
studytosky1 天前
【高并发内存池】线程缓存核心原理与实现
linux·服务器·git·缓存
Lanren的编程日记1 天前
Flutter 鸿蒙应用内存管理优化实战:对象池+智能缓存+泄漏检测,全方位提升应用稳定性
flutter·缓存·华为·harmonyos