146.LRU缓存

146. LRU 缓存

使用哈希表和双向链表解决(也可以LinkedHashMap)

用于操作链表的方法为removeNode, addToHead.

在put中:

如果不存在key,则为添加, ++size, 需要判断容量;

容量超过,则尾删, --size;

容量没超过, 则不删;

如果存在key, 则为修改, 不需要判断容量;

以上两步均为操作,因此都得addToHead.

java 复制代码
class Node{
    public int key, val;
    public Node prev;
    public Node next;
    public Node(int a, int b){
        this.key = a;
        this.val = b;
        this.prev = null;
        this.next = null;
    }
    public Node(){
        this.key = 0;
        this.val = 0;
        this.prev = null;
        this.next = null;
    }
}
class LRUCache {
    private Node head;
    private Node tail;
    private Map<Integer, Node>map = new HashMap<>();
    private int capacity;
    private int size;
    public LRUCache(int capacity) {
        this.size = 0;
        this.capacity = capacity;
        head = new Node();
        tail = new Node();
        head.next = tail;
        tail.prev = head;
    }
    
    public int get(int key) {
        if(!map.containsKey(key)){
            return -1;
        }
        Node temp = map.get(key);
        removeNode(temp);
        addToHead(temp);
        return temp.val;
    }
    
    public void put(int key, int value) {
        Node node = map.get(key);
        if(node == null){
            Node newNode = new Node(key, value);
            map.put(key, newNode);
            addToHead(newNode);
            ++size;
            if(size > capacity){
                Node tail1 = tail.prev;
                map.remove(tail1.key);
                removeNode(tail1);
                --size;
            }
        }else {
            node.val = value;
            removeNode(node);
            addToHead(node);
        }
    }

    public void removeNode(Node node){
        node.next.prev = node.prev;
        node.prev.next = node.next;
    }

    public void addToHead(Node node){
        node.next = head.next;
        node.prev = head;
        head.next = node;
        node.next.prev = node;
    }
}

先前我在实现put操作时使用了containsKey,这使得我原来的代码时间消耗很高

相关推荐
caihuayuan534 分钟前
升级element-ui步骤
java·大数据·spring boot·后端·课程设计
佩奇的技术笔记2 小时前
Java学习手册:单体架构到微服务演进
java·微服务·架构
zxctsclrjjjcph2 小时前
【高并发内存池】从零到一的项目之centralcache整体结构设计及核心实现
开发语言·数据结构·c++·链表
LLLLLindream2 小时前
Redis-商品缓存
数据库·redis·缓存
zm2 小时前
服务器多客户端连接核心要点(1)
java·开发语言
FuckPatience2 小时前
关于C#项目中 服务层使用接口的问题
java·开发语言·c#
柃歌2 小时前
【LeetCode Solutions】LeetCode 176 ~ 180 题解
数据结构·数据库·sql·算法·leetcode
大G哥2 小时前
加速LLM大模型推理,KV缓存技术详解与PyTorch实现
人工智能·pytorch·python·深度学习·缓存
天上掉下来个程小白2 小时前
缓存套餐-01.Spring Cache介绍和常用注解
java·redis·spring·缓存·spring cache·苍穹外卖
HackShendi3 小时前
记一次SSE数据被缓存导致实时性失效问题
缓存