398. Random Pick Index
https://leetcode.com/problems/random-pick-index/description/
Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.
Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge.
Example:
1 | int[] nums = new int[] {1,2,3,3,3}; |
Solution:
- space O(1), time O(n)
- use 1 slot to hold output. if the n^th index is found, it has 1/n probability to replace the slot. (can use mutiple slot and the answer will be same)
1 | import random as rd |
1 | # first try, use two slots |