1. Use a hash map <number, List<index>> to store the input array
2. Every time pick method invoke, get the list of index for given target number, get the random list index by rand.((max-min)+1)+min
public class Solution {
Map<Integer, List<Integer>> map;
Random rand;
public Solution(int[] nums) {
rand = new Random();
map = new HashMap<Integer, List<Integer>>();
for(int i = 0; i<nums.length; i++){
if(!map.containsKey(nums[i])){
map.put(nums[i], new ArrayList<Integer>());
}
map.get(nums[i]).add(i);
}
}
public int pick(int target) {
List<Integer> list = map.get(target);
if(list.size() == 1){
return list.get(0);
}
int listIndex = rand.nextInt(list.size());
return list.get(listIndex);
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/
Without extra space
public class Solution {
int[] nums;
Random rand;
public Solution(int[] nums) {
this.rand = new Random();
this.nums = nums;
}
public int pick(int target) {
int res = -1;
int upbound = 1;
for(int i=0; i<nums.length; i++){
if(nums[i] == target){
if(rand.nextInt(upbound) == 0){
res = i;
}
upbound++;
}
}
return res;
}
}