Given a blacklist B containing unique integers from [0, N), write a function to return a uniform random integer from [0, N) which is NOT in B.

Optimize it such that it minimizes the call to system’s Math.random().

idea:
so this question asks us to random generate something which is not in the black list B, and the range we are given is [0, N).
and we need to minimize the time of call in Math.random()

so that actually means we can’t use that “generate-check” procedures because that will significantly increasing our calls of random()

class Solution {

    public Solution(int N, int[] blacklist) {
        
    }
    
    public int pick() {
        
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(N, blacklist);
 * int param_1 = obj.pick();
 */

so how should we do sth to this problem? the producer is so simple that I can’t even know how to change anything, how are we gonna make sure that each time we randomly picked something, that’s 100 percent not in B?
for design problems like this, preprocess is a good way to save time when we call the method of this class, and when I say preprocess, I mean, preprocess in the constructor(this technique used in many design questions like the sum of range etc.)

然后我们后来发现用这种在构造器里面预处理方式做的design题目还不少。
Suppose N=10, blacklist=[3, 5, 8, 9], re-map 3 and 5 to 7 and 6.
LeetCode 710 Random Pick with Blacklist_其他

能想出这种方法的真的是天才。

class Solution {
    
    int M; //M is the number of integers from [0, N) which not in blacklist
    Random r;
    HashMap<Integer, Integer> map;

    public Solution(int N, int[] blacklist) {
        map = new HashMap<>();
        r = new Random();
        for (int b: blacklist) {
            map.put(b, -1);
        }
        
        M = N - map.size();
        
        for (int b: blacklist) {
            if (b < M) {
                while (map.containsKey(N - 1)) {
                    N--;
                }
                map.put(b, N - 1);//remaping b to N-1, so the key will be the element in blacklist, and the value will be the number it remapping. so each time we choose a one, we check if we need to remapping, if we need to remaping, then we do it. if it is not, then we use it.
                //this mechanism actually avoid that possiblity discard the random number rach time, it is genius
                N--;
            }
        }
    }
    
    public int pick() {
        int p = r.nextInt(M); //choose any integer from [0, M)
        if (map.containsKey(p)) { //if p is contained in map, then remapping it 
            return map.get(p);
            
        }
        return p;
    }
}