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;
    }
}
相关推荐
码农郁郁久居人下5 小时前
Redis的配置与优化
数据库·redis·缓存
Hsu_kk7 小时前
Redis 主从复制配置教程
数据库·redis·缓存
DieSnowK7 小时前
[Redis][环境配置]详细讲解
数据库·redis·分布式·缓存·环境配置·新手向·详细讲解
比花花解语9 小时前
Java中Integer的缓存池是怎么实现的?
java·开发语言·缓存
Lill_bin16 小时前
Lua编程语言简介与应用
开发语言·数据库·缓存·设计模式·性能优化·lua
一大颗萝卜17 小时前
【原创 架构设计】多级缓存的应用、常见问题与解决方式
redis·缓存·架构·caffeine·多级缓存
Java码农杂谈21 小时前
浅谈Tair缓存的三种存储引擎MDB、LDB、RDB
java·redis·分布式·后端·阿里云·缓存
DYS_000011 天前
阿里短信服务+Redis创建定时缓存
数据库·redis·缓存
day3ZY1 天前
清理C盘缓存的垃圾,专业清理C盘缓存垃圾的步骤与策略
缓存
day3ZY2 天前
清理C盘缓存的垃圾,专业清理C盘缓存垃圾与优化运行内存的策略
缓存