0%

LeetCode: 398. Random Pick Index

蓄水池抽样

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
Solution(vector<int> nums) {
_nums = nums;
srand(0);
}

int pick(int target)
{
int count=0, ret=-1;
for(int i=0;i<_nums.size();++i)
{
if(_nums[i]==target)
{
++count;
if(rand()%count==0)
ret=i;
}
}
return ret;
}

private:
vector<int> _nums;
};

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