Class Solution
- java.lang.Object
-
- g0701_0800.s0710_random_pick_with_blacklist.Solution
-
public class Solution extends Object
710 - Random Pick with Blacklist.Hard
You are given an integer
nand an array of unique integersblacklist. Design an algorithm to pick a random integer in the range[0, n - 1]that is not inblacklist. Any integer that is in the mentioned range and not inblacklistshould 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
Solutionclass:Solution(int n, int[] blacklist)Initializes the object with the integernand the blacklisted integersblacklist.int pick()Returns a random integer in the range[0, n - 1]and not inblacklist.
Example 1:
Input
[“Solution”, “pick”, “pick”, “pick”, “pick”, “pick”, “pick”, “pick”]
[[7, [2, 3, 5]], [], [], [], [], [], [], []]
Output: [null, 0, 4, 1, 6, 1, 0, 4]
Explanation:
Solution solution = new Solution(7, [2, 3, 5]); solution.pick(); // return 0, any integer from [0,1,4,6] should be ok. Note that for every call of pick, // 0, 1, 4, and 6 must be equally likely to be returned (i.e., with probability 1/4). solution.pick(); // return 4 solution.pick(); // return 1 solution.pick(); // return 6 solution.pick(); // return 1 solution.pick(); // return 0 solution.pick(); // return 4Constraints:
1 <= n <= 1090 <= blacklist.length <- min(105, n - 1)0 <= blacklist[i] < n- All the values of
blacklistare unique. - At most
2 * 104calls will be made topick.
-
-
Constructor Summary
Constructors Constructor Description Solution(int n, int[] blacklist)
-