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);
思路:一种是Reservoir sampling,也就是在target的count内进行random,如果 == 0,则取这个index;
class Solution {
private int[] A;
private Random random;
public Solution(int[] nums) {
this.A = nums;
this.random = new Random();
}
public int pick(int target) {
int count = 0;
int candidate = 0;
for(int i = 0; i < A.length; i++) {
if(A[i] == target && random.nextInt(++count) == 0) {
candidate = i;
}
}
return candidate;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/
思路2: 收集target的list,然后返回random index in the list;
class Solution {
HashMap<Integer, List<Integer>> hashmap;
public Solution(int[] nums) {
this.hashmap = new HashMap<>();
for(int i = 0; i < nums.length; i++) {
hashmap.putIfAbsent(nums[i], new ArrayList<>());
hashmap.get(nums[i]).add(i);
}
}
public int pick(int target) {
List<Integer> indexlist = hashmap.get(target);
Random random = new Random();
int index = random.nextInt(indexlist.size());
return indexlist.get(index);
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/