146. LRU 缓存

这道题只要把双向链表和哈希表连接起来就行,只是写起来有点麻烦了

java 复制代码
class LRUCache {
class DLinkedNode {
        int key;
        int value;
        DLinkedNode prev;
        DLinkedNode next;
        public DLinkedNode(){}
        public DLinkedNode(int _key, int _value) {key = _key;value = _value;}
    }

    private Map<Integer, DLinkedNode> cache = new HashMap<Integer, DLinkedNode>();
    private int size;
    private int capacity;
    private DLinkedNode head, tail;

    public LRUCache(int capacity) {
        this.size = 0;
        this.capacity = capacity;
        //使用伪头部和伪尾部
        head = new DLinkedNode();
        tail = new DLinkedNode();
        //双向链表
        head.next = tail;
        tail.prev = head;
    }
    
    public int get(int key) {
        DLinkedNode node = cache.get(key);   
        if(node == null){
            return -1;
        }
        //如果节点存在
        moveToHead(node);
        return node.value;
    }
    
    public void put(int key, int value) {
        //尝试从原来的双向哈希链表中获取
        DLinkedNode node = cache.get(key);
        if(node == null){
            //不存在创建新节点
            DLinkedNode newNode = new DLinkedNode(key, value);
            //添加进表
            cache.put(key,newNode);
            //添加到双向链表头部
            addToHead(newNode);
            ++size;
            if (size > capacity){
                //超出容量,删除尾部元素
                DLinkedNode tail = removeTail();
                //删除哈希表中对应项
                cache.remove(tail.key);
                --size;
            }
        }
        //存在节点,先定位再修改数据,并移到头部
        else{
            node.value = value;
            moveToHead(node);
        }

    }
    private void moveToHead(DLinkedNode node){
        removeNode(node);
        addToHead(node);
    }
    private void removeNode(DLinkedNode node){
        node.prev.next = node.next;
        node.next.prev = node.prev;
    }
    private void addToHead(DLinkedNode node){
        node.prev = head;
        node.next = head.next;f
        head.next.prev = node;
        head.next = node;
    }
    private DLinkedNode removeTail(){
        DLinkedNode res = tail.prev;
        removeNode(res);
        return res;
    }
}

/**
 * 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);
 */
相关推荐
小七-七牛开发者9 天前
TokenPilot:让 LLM Agent 长会话成本降 60%+ 的上下文管理
缓存·agent·token·context·上下文·推理成本
ofoxcoding17 天前
在AI API聚合平台配置DeepSeek V3.2提示词缓存实战:快速接入与成本优化指南
人工智能·spring·缓存·ai
NeilYuen17 天前
gRPC结合FAISS构建AI助手语义缓存模块(一):设计
人工智能·缓存·faiss
taocarts_bidfans17 天前
反向海淘跨境缓存架构优化:taocarts Redis分层缓存实战技术
redis·缓存·架构·反向海淘·taocarts
退休倒计时17 天前
【每日一题】LeetCode 146. LRU 缓存 TypeScript
算法·leetcode·缓存·typescript
炘爚17 天前
Linux——Redis
数据库·redis·缓存
小挪号底迪滴17 天前
Redis 和 MySQL 数据不一致怎么办?缓存更新策略实战
redis·mysql·缓存
闪电悠米17 天前
黑马点评-Redis ZSet-实现关注 Feed 流
服务器·网络·数据库·redis·缓存·junit·lua
Saniffer_SH18 天前
【高清视频】Gen6 服务器还没到,Gen6 SSD 怎么测?Emily 现场演示三种测试环境
人工智能·驱动开发·测试工具·缓存·fpga开发·计算机外设·压力测试