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;
    }
}
相关推荐
春生野草2 小时前
Redis
数据库·redis·缓存
万象.5 小时前
redis持久化:AOF和RDB
数据库·redis·缓存
cheungxiongwei.com5 小时前
深入解析 DNS 缓存与 TTL:工作原理、修改生效机制与优化策略
缓存
!chen6 小时前
Redis快速实现布隆过滤器
数据库·redis·缓存
xxxmine7 小时前
Redis 持久化详解:RDB、AOF 与混合模式
数据库·redis·缓存
what丶k8 小时前
SpringBoot3 缓存抽象深度实践:Caffeine+Redis多级缓存,穿透/雪崩/击穿防御全方案
数据库·redis·缓存
咖啡の猫8 小时前
Redis简单介绍
数据库·redis·缓存
爱吃大芒果8 小时前
Flutter for OpenHarmony 实战: mango_shop 购物车模块的状态同步与本地缓存处理
flutter·缓存·dart
源代码•宸10 小时前
Redis 攻略(Redis Object)
数据库·redis·后端·缓存·字符串·哈希表·type
heartbeat..10 小时前
Redis常见问题及对应解决方案(基础+性能+持久化+高可用全场景)
java·数据库·redis·缓存