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);
 */
相关推荐
AI技术新视界4 小时前
LLM 提示词缓存(Prompt Caching)的秘密
人工智能·缓存·llm·prompt
lsc_blog1 天前
年底还在招的岗位,先确认缺口和到岗要求
git·缓存·ci/cd·职场和发展·github
xixiaoyunya1 天前
Redis缓存三大问题实战:穿透、击穿、雪崩,我用一个电商秒杀场景讲清楚
数据库·redis·缓存
我不会起名字3221 天前
Redis 从 0 到 1(二十三):一个热 key 打到 10 万 QPS——hotkey 与本地缓存的 Go 实现
redis·缓存·go·qps·hotkey
真上帝的左手2 天前
30. 技术专题-‌应用框架组件-缓存-Redis
数据库·redis·分布式·缓存·中间件
bksczm2 天前
C++Redis开发(Ubuntu 22.04)
数据库·redis·缓存
goehou2 天前
缓存该删还是该改,LLM 服务里的双写问题
redis·缓存·llm·一致性·系统设计
利威尔xu3 天前
Go IM 源码实战(14):本地缓存快 3000 倍,失效却难 10 倍
后端·缓存·微服务·面试·golang