Random Pick Index
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); class Solution { int[] nums; Random rand; public Solution(int[] nums) { this.nums = nums; this.rand = new Random(); } public int pick(int target) { int count = 0; int sample = -1; for(int i = 0; i < nums.length; i++){ if(nums[i] == target){ count++; int x = rand.nextInt(count); if(x == 0){ sample = i; } } } return sample; } } a b c c c c sample = 2 3 ½ 3 ⅓ 2 ½ 2 ⅓ 4 ⅓ counter = 3; [0, 3) i = 3 index = 2, 3 counter = 1 2 sample = 2 0, 1, 2 sample 0 0 ½ 0 ½ * ⅔ = ⅓ 1 ½ 2 ⅓ counter 1, 2, 3 产生一个随机数,如果这个随机数等于0, 替换掉原来的index, 不然保留 sample = 0 counter = 1 for (int i = 1; i < … ;i++) { counter++; int random = randint(0, counter); if (random == 0) { 1/counter 替换掉原来的数字 sample = i; } } P(第三步保留的是0) = P(第二步是0
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);
posted on 2018-08-28 20:05 猪猪🐷 阅读(145) 评论(0) 收藏 举报
浙公网安备 33010602011771号