LeetCode //C - 382. Linked List Random Node

382. Linked List Random Node

Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen.

Implement the Solution class:

  • Solution(ListNode head) Initializes the object with the head of the singly-linked list head.
  • int getRandom() Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.
Example 1:

Input:

"Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"

\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]

Output:

null, 1, 3, 2, 2, 3

Explanation:

Solution solution = new Solution([1, 2, 3]);

solution.getRandom(); // return 1

solution.getRandom(); // return 3

solution.getRandom(); // return 2

solution.getRandom(); // return 2

solution.getRandom(); // return 3

// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.

Constraints:
  • The number of nodes in the linked list will be in the range [ 1 , 1 0 4 ] [1, 10^4] [1,104].
  • − 1 0 4 < = N o d e . v a l < = 1 0 4 -10^4 <= Node.val <= 10^4 −104<=Node.val<=104
  • At most 1 0 4 10^4 104 calls will be made to getRandom.

From: LeetCode

Link: 382. Linked List Random Node


Solution:

Ideas:
  1. solutionCreate: Initializes the Solution object, stores the head of the linked list, and seeds the random number generator.

  2. solutionGetRandom: Implements reservoir sampling to randomly select a node with equal probability. It iterates over the entire linked list and replaces the current result with a random chance, ensuring each node has an equal chance of being picked.

  3. solutionFree: Frees the memory allocated for the Solution object.

Code:
c 复制代码
// Definition for singly-linked list.
struct {
    int val;
    struct ListNode *next;
}ListNode;

typedef struct {
    struct ListNode* head;
} Solution;

Solution* solutionCreate(struct ListNode* head) {
    Solution* obj = (Solution*) malloc(sizeof(Solution));
    obj->head = head;
    srand(time(NULL)); // Initialize random number generator
    return obj;
}

int solutionGetRandom(Solution* obj) {
    struct ListNode* current = obj->head;
    int result = current->val;
    int i = 1;
    
    while (current != NULL) {
        // Pick a random number in range [0, i]
        if (rand() % i == 0) {
            result = current->val; // Replace the result with current node's value
        }
        current = current->next;
        i++;
    }
    return result;
}

void solutionFree(Solution* obj) {
    free(obj);
}

/**
 * Your Solution struct will be instantiated and called as such:
 * Solution* obj = solutionCreate(head);
 * int param_1 = solutionGetRandom(obj);
 * solutionFree(obj);
 */
相关推荐
QT 小鲜肉11 分钟前
【Git、GitHub、Gitee】按功能分类汇总Git常用命令详解(超详细)
c语言·网络·c++·git·qt·gitee·github
AI科技星39 分钟前
张祥前统一场论动量公式P=m(C-V)误解解答
开发语言·数据结构·人工智能·经验分享·python·线性代数·算法
海琴烟Sunshine42 分钟前
leetcode 345. 反转字符串中的元音字母 python
python·算法·leetcode
geobuilding1 小时前
将大规模shp白模贴图转3dtiles倾斜摄影,并可单体化拾取建筑
算法·3d·智慧城市·数据可视化·贴图
jghhh011 小时前
基于高斯伪谱法的弹道优化方法及轨迹仿真计算
算法
mm-q29152227293 小时前
【天野学院5期】 第5期易语言半内存辅助培训班,主讲游戏——手游:仙剑奇侠传4,端游:神魔大陆2
人工智能·算法·游戏
MoRanzhi12033 小时前
Python 实现:从数学模型到完整控制台版《2048》游戏
数据结构·python·算法·游戏·数学建模·矩阵·2048
散峰而望3 小时前
基本魔法语言函数(一)(C语言)
c语言·开发语言·编辑器·github
2401_841495643 小时前
【数据结构】基于BF算法的树种病毒检测
java·数据结构·c++·python·算法·字符串·模式匹配
蒙奇D索大4 小时前
【算法】递归算法实战:汉诺塔问题详解与代码实现
c语言·考研·算法·面试·改行学it