398.|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);
Solution:Reservoir Sampling 思路:
Time Complexity: O(N) Space Complexity: O(N)
【398.|398. Random Pick Index】Solution Code:
public class Solution {int[] nums;
Random rnd;
public Solution(int[] nums) {
this.nums = nums;
this.rnd = new Random();
}public int pick(int target) {
int result = -1;
int count = 0;
for (int i = 0;
i < nums.length;
i++) {
if (nums[i] != target)
continue;
if (rnd.nextInt(++count) == 0)
result = i;
}return result;
}
}
推荐阅读
- python|python random使用方法
- Python之random库的常用函数有哪些
- [Toddler's|[Toddler's Bottle]-random
- 8月影单来了,你会pick哪一部呢
- 穆勒鞋非要pick一双我选EDGII
- 第七届CIPE深圳授权展,我pick呆狸!
- element-ui|element-ui el-date-picker 时间日期组件设置时间日期范围.2
- el-date-picker日期框点击失效问题
- 仿照DatePickerFragment实现的TimePickerFragment
- 对话框-DialogFragment+AlertDialog+Calendar+DatePicker