每日一题《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);
}
相关推荐
Dante79833 分钟前
【数据结构】二叉搜索树、平衡搜索树、红黑树
数据结构·c++·算法
驼驼学编程1 小时前
决策树,Laplace 剪枝与感知机
算法·决策树·剪枝
坚强小葵1 小时前
实验8-2-1 找最小的字符串
c语言·算法
apcipot_rain1 小时前
【密码学——基础理论与应用】李子臣编著 第三章 分组密码 课后习题
python·算法·密码学
lucky1_1star2 小时前
FX-函数重载、重写(覆盖)、隐藏
java·c++·算法
KuaCpp3 小时前
蓝桥杯15届省C
算法·蓝桥杯
奔跑的废柴4 小时前
LeetCode 738. 单调递增的数字 java题解
java·算法·leetcode
武乐乐~5 小时前
欢乐力扣:合并区间
算法·leetcode·职场和发展
安忘10 小时前
LeetCode 热题 -189. 轮转数组
算法·leetcode·职场和发展