leetcode 398. Random Pick Index

本文介绍了一种基于水塘抽样算法解决随机选取数组中特定目标元素索引的问题。通过对不同数组长度的分析,逐步推导出适用于任意长度数组的高效算法。该算法能够确保每个符合条件的目标元素被选中的概率相等。

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

398. Random Pick Index

Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.

Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge.

Example:

int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);

// pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(3);

// pick(1) should return 0. Since in the array only nums[0] is equal to 1.
solution.pick(1);

和382题类似,直接用水塘抽样的思想做。


1) 长度为1,只有一个数据,直接返回即可,此数据被返回的概率为1.

2)长度为2,当读取第一数据时,我们发现并不是最后一个数据,我们不能直接返回,因为数据流还没结束,继续读取,到第二数据的时候,发现已经结束。所以现在的问题就是等概率返回其中的一个,显然概率为0.5。所以此时我们可以生成一个0到1的随机数p,如果p小于0.5,返回第二个,如果大于0.5,返回第一个。显然此时两个数据被返回的概率是一样的。

3)长度为3,我们可以事先分析得到,为了满足题意,需要保证每个数据返回的概率都是1/3。接下来分析数据流,首先读取第一个数据,然后在读取第二个数据,此时可以按2)处理,保留一个数据,每个数据显然为1/2。此时读取第三个数据,发现到尾部了,为了满足题意,此时需要一1/3的概率决定是否取此数据。现在分析前两个数是否也是以1/3的概率返回,如果是则总体都满足。数据1和数据2同时留下的概率为:1/2 *(1-1/3)= 1/3。1/2只在数据1和数据2pk时,能留下的概率,1-1/3指数据3不被留下的概率。所以,对长度为3的数据流,在读取第三个数据时,我们可以生成一个0到1的随机数p,如果p小于1/3,返回第三个数据,否则,返回前面两个pk留下的数据。

由上面的分析,我们可以得出结论,在取第n个数据的时候,我们生成一个0到1的随机数p,如果p小于1/n,保留第n个数。大于1/n,继续保留前面的数。直到数据流结束,返回此数。



如果用map转存一次会MLE。

class Solution {
public:
    Solution(vector<int> nums) 
    {
        for (int i = 0; i < nums.size(); i++)
            mp[nums[i]].push_back(i);
    }
    
    int pick(int target) 
    {
        int cur = mp[target][0];  
        int n = 1;
        int k = 1;
        while (k < mp[target].size())  
        {    
            n ++;  
            if ((rand() % n) == 0) //如果 随机出来的数  
                cur = mp[target][k];
            k++;
        }  
        return cur;  
    }
private:
    map<int, vector<int>> mp;
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * int param_1 = obj.pick(target);
 */


1、因此将map换为vector

2、第二版中开始错把n++写在if下面,这样会错。因为就算rand() %n != 0 也需要n++!!!


class Solution {
public:
    Solution(vector<int> nums) 
    {
        num = nums;
    }
    
    int pick(int target) 
    {
        int n = 1;
        int cur;
        for (int i = 0; i < num.size(); i++)
        {
            if (num[i] == target &&  (rand() % n++) == 0)  
            {
                cur = i;
            }    
        }  
        return cur;  
    }
private:
    vector<int> num;
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * int param_1 = obj.pick(target);
 */




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值