398 Random Pick Index

# 1. Question

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:
1
int[] nums = new int[] {1,2,3,3,3};
2
Solution solution = new Solution(nums);
3
4
// pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
5
solution.pick(3);
6
7
// pick(1) should return 0. Since in the array only nums is equal to 1.
8
solution.pick(1);
Copied!

# 2. Implementation

(1) Reservoir Sampling
1
class Solution {
2
Random rand;
3
int[] nums;
4
5
public Solution(int[] nums) {
6
this.nums = nums;
7
rand = new Random();
8
}
9
10
public int pick(int target) {
11
int res = -1;
12
int count = 0;
13
14
for (int i = 0; i < nums.length; i++) {
15
if (nums[i] == target && rand.nextInt(++count) == 0) {
16
res = i;
17
}
18
}
19
return res;
20
}
21
}
22
23
/**
24
* Your Solution object will be instantiated and called as such:
25
* Solution obj = new Solution(nums);
26
* int param_1 = obj.pick(target);
27
*/
Copied!

# 3. Time & Space Complexity

Reservoir Sampling: 时间复杂度O(n), 空间复杂度O(n)