【hot100-java】LRU 缓存

链表篇

灵神题解

java 复制代码
class LRUCache {
    private static class Node{
        int key,value;
        Node prev,next;

        Node (int k,int v){
            key=k;
            value=v;
        }
    }
    private final int capacity;
    //哨兵节点
    private final Node dummy=new Node(0,0);
    private final Map<Integer,Node> keyToNode =new HashMap<>();

    public LRUCache(int capacity) {
        this.capacity=capacity;
        dummy.prev=dummy;
        dummy.next=dummy;
    }
    
    public int get(int key) {
           Node node=getNode(key);
           return node!=null?node.value:-1;
    }
    
    public void put(int key, int value) {
          Node node=getNode(key);
          //有书则更新
          if(node!=null){
            node.value=value;
            return;
          }
          node=new Node(key,value);
          keyToNode.put(key,node);
          //放在最上面
          pushFront(node);
          //书太多了
          if(keyToNode.size()>capacity){
              Node backNode=dummy.prev;
              keyToNode.remove(backNode.key);
              //去掉最后一本书
              remove(backNode);
          }
    }

    //取节点
    private Node getNode(int key){
        //没有这本书
        if(!keyToNode.containsKey(key)){
            return null;
        }
        //有这本书
        Node node=keyToNode.get(key);
        //抽出来
        remove(node);
        //放在最上面
        pushFront(node);
        return node;
    }

    //删除一个节点(抽出一本书)
    private void remove(Node x){
        x.prev.next=x.next;
        x.next.prev=x.prev;
    }

    //链表头添加节点
    private void pushFront(Node x){
        x.prev=dummy;
        x.next=dummy.next;
        x.prev.next=x;
        x.next.prev=x;
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */

背题

相关推荐
Charles_go23 分钟前
C#中级8、什么是缓存
开发语言·缓存·c#
q***040525 分钟前
Nginx 缓存清理
运维·nginx·缓存
松涛和鸣1 小时前
14、C 语言进阶:函数指针、typedef、二级指针、const 指针
c语言·开发语言·算法·排序算法·学习方法
yagamiraito_3 小时前
757. 设置交集大小至少为2 (leetcode每日一题)
算法·leetcode·go
星释3 小时前
Rust 练习册 57:阿特巴什密码与字符映射技术
服务器·算法·rust
星期天23 小时前
3.0 C语⾔内存函数:memcpy memmove memset memcmp 数据在内存中的存储:整数在内存中的存储 ⼤⼩端字节序和字节序判断
c语言·数据结构·进阶·内存函数·数据内存存储
无敌最俊朗@3 小时前
力扣hot100-141.环形链表
算法·leetcode·链表
movie__movie4 小时前
秒杀库存扣减可以用redis原子自增么
数据库·redis·缓存
向着光芒的女孩5 小时前
【IDEA】关不了的Proxy Authentication弹框探索过程
java·ide·intellij-idea
Filotimo_5 小时前
Spring Boot 整合 JdbcTemplate(持久层)
java·spring boot·后端