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;
    }
}
相关推荐
小毛驴85010 小时前
redis 如何持久化
数据库·redis·缓存
Kevinyu_17 小时前
Redisson
java·redis·缓存
代码老y18 小时前
Redis 生产实战 7×24:容量规划、性能调优、故障演练与成本治理 40 条军规
数据库·redis·缓存
dexianshen20 小时前
缓存雪崩、缓存穿透,缓存击穿
缓存
许苑向上2 天前
分布式缓存击穿以及本地击穿解决方案
java·分布式·缓存
L_qingting3 天前
Redis 主从复制
数据库·redis·缓存
代码老y3 天前
在百亿流量面前,让“不存在”无处遁形——Redis 缓存穿透的极限攻防实录
数据库·redis·缓存
阿巴~阿巴~3 天前
深入解析:磁盘级文件与内存级(被打开)文件的本质区别与联系
linux·运维·服务器·数据库·缓存
Dajiaonew3 天前
Redis主从同步原理(全量复制、增量复制)
数据库·redis·缓存
秋恬意3 天前
redis红锁
数据库·redis·缓存