Medium
Quiz
#398 Random Pick Index
APPROACH
An integer array nums may contain duplicate values. Build a data structure that, given any target guaranteed to appear in nums, returns one of the positions where target occurs with equal probability for each occurrence.
Implement the Solution class:
- Solution(int[] nums) Constructs the object from array nums.
- int pick(int target) Returns a uniformly random index i satisfying nums[i] == target.
Example 1:
Input
["Solution", "pick", "pick", "pick"]
[[[1, 2, 3, 3, 3]], [3], [1], [3]]
Output
[null, 4, 0, 2]
Example 2:
Explanation
Solution solution = new Solution([1, 2, 3, 3, 3]);
solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(1); // It should return 0. Since in the array only nums[0] is equal to 1.
solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
1 of 4
1:00
What is the optimal approach for this problem?