每日一题《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);
}
相关推荐
GIS瞧葩菜1 小时前
Cesium 轴拖拽 + 旋转圈拖拽 核心数学知识
人工智能·算法·机器学习
m0_686041611 小时前
C++中的适配器模式变体
开发语言·c++·算法
txzrxz1 小时前
结构体排序,双指针,单调栈
数据结构·算法·双指针算法·单调栈·结构体排序
AndrewHZ1 小时前
【AI黑话日日新】什么是AI智能体?
人工智能·算法·语言模型·大模型·llm·ai智能体
wWYy.1 小时前
算法:二叉树最大路径和
数据结构·算法
葱明撅腚1 小时前
利用Python挖掘城市数据
python·算法·gis·聚类
We་ct1 小时前
LeetCode 36. 有效的数独:Set实现哈希表最优解
前端·算法·leetcode·typescript·散列表
weixin_395448912 小时前
main.c_cursor_0129
前端·网络·算法
CS创新实验室2 小时前
《计算机网络》深入学:路由算法与路径选择
网络·计算机网络·算法
一条大祥脚2 小时前
ABC357 基环树dp|懒标记线段树
数据结构·算法·图论