leetcode 随机概率 水塘抽样

本文介绍了一种使用水塘抽样算法从链表中随机选择一个节点的方法。通过维护一个大小为1的水塘,每次遍历到新的节点时,以1/i的概率替换水塘中的值,确保每个节点被选中的概率相等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
 /*
 水塘抽样:维护一个大小为1的水塘,由于确定head一定存在,定义res返回head->val的值,然后让head指向下一个节点,同时定义一个变量i,i初始化为2,当cur不为空的时候,循环在[0,i-1]中取值,变量i自增1,cur指向下一个位置,如果随机生成数为0的话,交换水塘的值和当前遍历的值。这样保证每个数字的概率。
 */
class Solution {
public:
    /** @param head The linked list's head.
        Note that the head is guaranteed to be not null, so it contains at least one node. */
    Solution(ListNode* head) {
        this->head=head;
    }

    /** Returns a random node's value. */
    int getRandom() {
        int res=head->val;
        int i=2;

        ListNode *cur=head->next;
        while(cur){
            int j=rand()%i;
            if(j==0) res=cur->val;
            ++i;
            cur=cur->next;
        }
        return res;
    }
    private:
    ListNode *head;
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(head);
 * int param_1 = obj.getRandom();
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值