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;
    }
}
相关推荐
忍冬行者33 分钟前
清理三主三从redis集群的过期key和键值超过10M的key
数据库·redis·缓存
TimberWill37 分钟前
使用Redis队列优化内存队列
数据库·redis·缓存
梦里不知身是客117 小时前
redis的缓存击穿原因
redis·缓存·bootstrap
GGBondlctrl10 小时前
【Redis】从单机架构到分布式,回溯架构的成长设计美学
分布式·缓存·架构·微服务架构·单机架构
不穿格子的程序员11 小时前
Redis篇4——Redis深度剖析:内存淘汰策略与缓存的三大“天坑”
数据库·redis·缓存·雪崩·内存淘汰策略
想搞艺术的程序员14 小时前
Go语言环形队列:原理剖析、编程技巧与核心优势
后端·缓存·golang
T1ssy14 小时前
深入解析Redis三大缓存问题:穿透、击穿、雪崩及解决方案
数据库·redis·缓存
木易 士心15 小时前
NestJS 核心揭秘:InstanceWrapper 的艺术与前端缓存新思路
前端·缓存
Haooog15 小时前
Redis面试题(不定时更新)
数据库·redis·缓存·面试
孙同学_15 小时前
【Linux篇】线程互斥、同步与线程池设计:原理与实践
数据库·redis·缓存