LeetCode 710 Random Pick with Blacklist

263 篇文章 1 订阅
12 篇文章 0 订阅

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.
在这里插入图片描述

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

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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值