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);
解答:
这道题其实就是用水塘抽样法。
参考维基百科
水塘抽样法
什么事水塘抽样法呢,就是对于N个数取k个数,我们让k放入水塘,考虑后面的数,对于j>k的每个数j,考虑从1到j生成一个数r,假如r小于等于k,那么就交换r和j位置的数。
例如
例如在一很大,但未知确实行数的文字档中抽取任意一行。如果要确保每一行抽取的概率相等,即是说如果最后发现文字档共有N行,则每一行被抽取的概率均为1/N,则有如下算法:
对于第一行以后的每个数,例如下标为2的数,我们以1/2的概率选择是否将第二行替换第一个行,对于下标为3的数,以1/3的概率选择是否将第三行替换第一行
,概述来说
定义取出的行号为choice,第一次直接以第一行作为取出行 choice ,而后第二次以二分之一概率决定是否用第二行替换 choice ,第三次以三分之一的概率决定是否以第三行替换 choice ……,以此类推。由上面的分析我们可以得出结论,在取第n个数据的时候,我们生成一个0到1的随机数p,如果p小于1/n,保留第n个数。大于1/n,继续保留前面的数。直到数据流结束,返回此数,算法结束。
参考几个博客
编程珠玑
水塘抽样(Reservoir Sampling)问题
具体到这道题就是说,考虑一直走然后一直碰到target,每碰到一次target统计有多少个数等于target,每统计多一个数在0到统计的次数之间产生一个随机数,假如这个随机数为0,那么就记录下这个target的下标。这里面就是说,第一次碰到,有1的概率,第二次有1/2的概率取第二个的下标,第三次有1/3.依次类推。
class Solution {
public:
Solution(vector<int> nums):v(nums)
{
};
int pick(int target) {
int cnt=0,res=-1;
for(int i=0;i<v.size();i++)
{
if(v[i]!=target) continue;
cnt++;
if(rand()%cnt==0) res=i;
}
return res;
}
private:
vector<int> v;
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/