leetcode-382.链表随机节点

数学问题-随机与取样


题目详情

给你一个单链表,随机选择链表的一个节点,并返回相应的节点值。每个节点 被选中的概率一样 。
实现 Solution 类:
Solution(ListNode head) 使用整数数组初始化对象。
int getRandom() 从链表中随机选择一个节点并返回该节点的值。链表中所有节点被选中的概率相等。


示例:

示例

输入
["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"]
[[[1, 2, 3]], [], [], [], [], []]
输出
[null, 1, 3, 2, 2, 3]

解释
Solution solution = new Solution([1, 2, 3]);
solution.getRandom(); // 返回 1
solution.getRandom(); // 返回 3
solution.getRandom(); // 返回 2
solution.getRandom(); // 返回 2
solution.getRandom(); // 返回 3
// getRandom() 方法应随机返回 1、2、3中的一个,每个元素被返回的概率相等。

思路:
不同于数组,在未遍历完链表前,我们无法知道链表的总长度。这里我们就可以使用水库采
样:遍历一次链表,在遍历到第 m 个节点时,有 1/m 的概率选择这个节点覆盖掉之前的节点选择。
简单证明:

证明

我的代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution 
{
    ListNode* h;
public:
    Solution(ListNode* head) :h(head) {} //将头节点用h存下来
    
    int getRandom() 
    {
        int ans = h->val; //初始化ans为头结点val
        ListNode* node = h->next; //利用node往后遍历
        int i = 2;  //因为此时node是第2个节点,所以i初始化为2
        while (node) // 遍历到末尾
        {
            //随机生成一个[0,i)的随机数,如果是0,
            //就把答案改为该节点的数(1/i的概率)
            if ((rand() % i) == 0)
            ans = node->val;
            //否则就继续往后遍历节点
            ++i;
            node = node->next;
        }
        return ans;
    }
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution* obj = new Solution(head);
 * int param_1 = obj->getRandom();
 */
posted @ 2022-07-22 17:52  ggaoda  阅读(4)  评论(0编辑  收藏  举报  来源