Poison

398. Random Pick Index

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
private final int[] nums;

public Solution(int[] nums) {
this.nums = nums;
}

public int pick(int target) {
int index = -1, bound = 1;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == target && ThreadLocalRandom.current().nextInt(bound++) == 0) {
index = i;
}
}

return index;
}
}
Reference

398. Random Pick Index