710. Random Pick with Blacklist
710. Random Pick with Blacklist
Description
Difficulty: Hard
Related Topics: Array, Hash Table, Math, Binary Search, Sorting, Randomized
You are given an integer n
and an array of unique integers blacklist
. Design an algorithm to pick a random integer in the range [0, n - 1]
that is not in blacklist
. Any integer that is in the mentioned range and not in blacklist
should be equally likely to be returned.
Optimize your algorithm such that it minimizes the number of calls to the built-in random function of your language.
Implement the Solution
class:
Solution(int n, int[] blacklist)
Initializes the object with the integern
and the blacklisted integersblacklist
.int pick()
Returns a random integer in the range[0, n - 1]
and not inblacklist
.
Example 1:
1 | Input |
Constraints:
- 1 <= n <= 109
- 0 <= blacklist.length <= min(105, n - 1)
0 <= blacklist[i] < n
- All the values of
blacklist
are unique. - At most 2 * 104 calls will be made to
pick
.
Hints/Notes
- Use map
Solution
Language: C++
1 | class Solution { |