398. Random Pick Index (Medium)
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 1: Reservoir Sampling O(n); O(1)
int[] nums;
Random rand;
public RandomPickIndex(int[] nums) {
this.nums = nums;
this.rand = new Random();
}
public int pick(int target) {
int res = -1;
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != target) {
continue;
} else if (rand.nextInt(++count) == 0) {
res = i;
}
}
return res;
}
Follow Up:
1.find index of maximum number in array, if multiple maximum numbers occurs, return a random index
public int findIndexOfMax(int[] nums) {
int res = -1;
int max = Integer.MIN_VALUE;
int count = 0;
Random rand = new Random();
for (int i = 0; i < nums.length; i++) {
if (nums[i] > max) {
max = nums[i];
count = 0;
} else if (nums[i] == max) { //要加else,不然要重复判断
if (rand.nextInt(++count) == 0) {
res = i;
}
}
}
return res;
}
public static void main(String[] args) {
RandomPickIndex test = new RandomPickIndex();
int[] nums = {1,2,3,3,3};
System.out.println(test.findIndexOfMax(nums));
}