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;
    }
}
相关推荐
上官浩仁3 小时前
springboot redisson 缓存入门与实战
spring boot·redis·缓存
络76 小时前
Redis 非缓存核心场景及实例说明
数据库·redis·缓存
土了个豆子的9 小时前
03.缓存池
开发语言·前端·缓存·visualstudio·c#
YUELEI11811 小时前
langchain 缓存 Caching
缓存·langchain
孤独的人11 小时前
WordPress 性能优化:从插件到 CDN 的全方位缓存设置指南
spring·缓存·性能优化
MAGICIAN...1 天前
【Redis】--持久化机制
数据库·redis·缓存
我真的是大笨蛋1 天前
JVM调优总结
java·jvm·数据库·redis·缓存·性能优化·系统架构
拾忆,想起1 天前
Redis复制延迟全解析:从毫秒到秒级的优化实战指南
java·开发语言·数据库·redis·后端·缓存·性能优化
破烂儿1 天前
基于机器学习的缓存准入策略研究
人工智能·机器学习·缓存
参.商.1 天前
【Day21】146.LRU缓存 (Least Recently Used)
leetcode·缓存·golang