Math.random() solution, but runtime only beats 5%:
class Solution {
HashMap<Integer, ArrayList<Integer>> map = new HashMap<>();
public Solution(int[] nums) {
for (int i = 0; i < nums.length; i++) {
ArrayList<Integer> list = new ArrayList<>();
if (map.containsKey(nums[i])) {
list = map.get(nums[i]);
}
list.add(i);
map.put(nums[i], list);
}
}
public int pick(int target) {
if (!map.containsKey(target)) return 0;
ArrayList<Integer> list = map.get(target);
int len = list.size();
int rand = (int)(Math.random() * len);
return list.get(rand);
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/
With reservoir sampling, runtime beats 90%:
class Solution {
int[] nums;
Random rand;
public Solution(int[] nums) {
this.nums = nums;
this.rand = new Random();
}
public int pick(int target) {
int result = -1;
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != target) {
continue;
}
if (rand.nextInt(++count) == 0) {
result = i;
}
}
return result;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/
Math.random() solution, but runtime only beats 5%:
With reservoir sampling, runtime beats 90%: