This is a similar problem with: 382. Linked List Random Node
The following is my solution, which is easy to understand:
class Solution { Map<Integer,List<Integer>> map = new HashMap<>(); Random r = new Random(); public Solution(int[] nums) { for(int i=0;i<nums.length;i++){ map.putIfAbsent(nums[i], new ArrayList<>()); map.get(nums[i]).add(i); } } public int pick(int target) { List<Integer> index = map.get(target); int randomIndex = r.nextInt(index.size()); return index.get(randomIndex); } }
The following is the other solution, but not very easy to understand:
class Solution { private int[] nums; private Random r = new Random(); public Solution(int[] nums) { this.nums = nums; } public int pick(int target) { int res = 0; int count = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] == target){ count++; if(r.nextInt(count) == count-1) res = i; } } return res; } }