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);
*/