1.题目
https://leetcode-cn.com/problems/random-pick-index/
2.题解
蓄水池抽样
其思路就是循环之后先判断一下这个数在数组中的索引,
然后随机选出来一个数据,
单链
3.代码
class Solution {
int[] nums;
public Solution(int[] nums) {
this.nums=nums;
}
public int pick(int target) {
int result=0;
int number=0;
for (int i = 0; i < nums.length ; i++) {
if(nums[i]==target){
number++;
Random ran=new Random();
if(ran.nextInt(number)==0){
result=i;
}
}
}
return result;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/