AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

HOT100-33.LRU 缓存

作者: 作者的头像   tle_machine ,  2025-06-08 22:59:57 · 江西 ,  所有人可见 ,  阅读 3


0


题目

12.png

题目链接

https://leetcode.cn/problems/lru-cache/?envType=study-plan-v2&envId=top-100-liked

解题思路

采用哈希表和双向链表的方式。其实我最开始想用队列的方式来维持,后面发现不现实,因为要动态的删除最久未使用元素。

相关代码

class LRUCache {
    Node head,tail;
    int len=0;
    Map<Integer,Node> hash = new HashMap<>();
    public LRUCache(int capacity) {
        len = capacity;
        head = new Node(-1,-1);
        tail = new Node(-1,-1);
        head.right = tail;
        tail.left = head;
    }
    public int get(int key) {
        Node temp = hash.get(key);
        if(temp==null) return -1;
        remove(temp);
        insert(temp);
        return temp.value;
    }
    public void put(int key, int value) {
        Node temp = hash.get(key);
        if(temp==null){
            if(hash.size()==len){
                hash.remove(tail.left.key);
                remove(tail.left);
            }
            hash.put(key,new Node(key,value));
            insert(hash.get(key));
        }   
        else{
            temp.value = value;
            remove(temp);
            insert(temp);
        } 
    }
    public void remove(Node p){
        p.left.right = p.right;
        p.right.left = p.left;
    }
    public void insert(Node p){
        p.right = head.right;
        head.right.left = p;
        head.right = p;
        p.left = head;
    }
}
class Node {
    int key,value;
    Node left,right;
    public Node(int key,int value){
        this.key = key;
        this.value = value;
    }
}

0 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息