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;
    }
}
相关推荐
MarkHard1235 小时前
如何利用redis使用一个滑动窗口限流
数据库·redis·缓存
心想事成的幸运大王6 小时前
Redis的过期策略
数据库·redis·缓存
wuyunhang12345612 小时前
Redis---集群模式
数据库·redis·缓存
没有bug.的程序员14 小时前
Redis 大 Key 与热 Key:生产环境的风险与解决方案
java·数据库·redis·缓存·热key·大key
wuyunhang12345614 小时前
Redis----缓存策略和注意事项
redis·缓存·mybatis
零雲14 小时前
除了缓存,我们还可以用redis做什么?
数据库·redis·缓存
梦中的天之酒壶14 小时前
多级缓存架构
缓存·架构
We....14 小时前
Java 分布式缓存实现:结合 RMI 与本地文件缓存
java·分布式·缓存
森林-17 小时前
MyBatis 从入门到精通(第三篇)—— 动态 SQL、关联查询与查询缓存
sql·缓存·mybatis
虫小宝17 小时前
返利软件的分布式缓存架构:Redis集群在高并发场景下的优化策略
分布式·缓存·架构