每日一题《leetcode--382.链表随机结点》

https://leetcode.cn/problems/linked-list-random-node/


这道题我们首先看到题目中的要求:在单链表中随机选取一个链表中的结点,要使每个结点被选取的概率是一样的。

当我们看到随机这两个字时,应该就会想起rand()这个函数。接着我们把使用这个函数生成的随机值与链表的长度进行模运算,这样子求出的结果就不会大于链表长度。

复制代码
//用数组存储该链表
typedef struct {
    int* arr;
    int length;
} Solution;


Solution* solutionCreate(struct ListNode* head) {
    Solution* obj = (Solution*)malloc(sizeof(Solution));
    obj->length = 0;

    struct ListNode* Node = head;
    //记录链表长度
    while(Node)
    {
        ++obj->length;
        Node = Node->next;
    }

    obj->arr = (int*)malloc(sizeof(int) * obj->length);
    Node = head;
    //将链表节点中的值赋值给数组
    for(int i =0; i<obj->length;i++)
    {
        obj->arr[i] = Node->val;
        Node = Node->next;
    }

    return obj;
}

int solutionGetRandom(Solution* obj) {
    //rand生成的随机值 % 链表长度 的值不会大于链表长度
    return obj->arr[rand() % obj->length];
}

void solutionFree(Solution* obj) {
    free(obj->arr);
    free(obj);
}
相关推荐
地平线开发者4 小时前
J6B vio scenario sample
算法
BothSavage16 小时前
Trae远程开发中DeepSeek自定义模型4054错误的排查与修复
算法
小林ixn16 小时前
从暴力到KMP:一道题彻底搞懂字符串匹配的前世今生
算法
烬羽17 小时前
字符串算法入门:从反转字符串到回文判断,面试不再慌
算法·面试
先吃饱再说1 天前
判断回文字符串,从一行代码到双指针优化
算法
黄敬峰1 天前
深入理解算法核心:从递归思想、数组扁平化到快速排序
算法
得物技术2 天前
从狂野代码到按目标生产:得物推荐 AI Harness 的工程化实践|AICon 演讲整理
人工智能·算法·架构
AI小老六2 天前
SkillOpt 架构拆解:把 Skill 文本当参数,用执行轨迹训练 Agent
后端·算法·ai编程