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);解析:一个概率题,假如数组中一个有k个target,则每个target的概率相同即为1/k,rand()%k==0的概率即为1/k,当遍历到第i个与target相同的元素时,且最后pick的下标为i时的概率p=1/i*(i/(i+1))*...*(k-1)/k=1/k;即每次遍历到target时,把结果更新为当前i时的概率为rand()%i==0的概率。注:本题由于数组很大
代码:
class Solution {
public:
vector<int> num;
Solution(vector<int> nums) {
num=nums;
}
int pick(int target) {
int length=num.size();
int indexnum=-1;
int count=0;
for (int i=0; i<num.size(); i++)
{
if (num[i]==target)
{
count++;
if (indexnum==-1)
indexnum=i;
else
{
indexnum=rand()%count?(indexnum):i;
}
}
}
return indexnum;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/