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;
    }
}
相关推荐
fengxin_rou19 小时前
Redis从零到精通第二篇:redis常见的命令
数据库·redis·缓存
云存储小天使21 小时前
GooseFS 推出元数据发现功能 —— 向更智能的缓存服务迈进
缓存
晓131321 小时前
第七章:Redis高级最佳实践详解
redis·分布式·缓存
知识即是力量ol2 天前
基于 Redis 实现白名单,黑名单机制详解及应用场景
数据库·redis·缓存
fengxin_rou2 天前
Redis 从零到精通:第一篇 初识redis
数据库·redis·缓存
陌上丨2 天前
Redis内存使用率在95%以上,请问是什么原因?如何解决?
数据库·redis·缓存
dawdo2222 天前
自己动手从头开始编写LLM推理引擎(9)-KV缓存实现和优化
缓存·llm·transformer·qwen·kv cache
小北方城市网2 天前
RabbitMQ 生产级实战:可靠性投递、高并发优化与问题排查
开发语言·分布式·python·缓存·性能优化·rabbitmq·ruby
陌上丨2 天前
什么是Redis的大Key和热Key?项目中一般是怎么解决的?
数据库·redis·缓存
小园子的小菜2 天前
深入剖析HBase HFile原理:文件结构、Block协作与缓存机制
数据库·缓存·hbase