710. Random Pick with Blacklist - LeetCode

Posted okokabcd

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了710. Random Pick with Blacklist - LeetCode相关的知识,希望对你有一定的参考价值。

Question

710. Random Pick with Blacklist

技术分享图片

Solution

题目大意:给一个N,表示一个范围[0,N),给一个黑名单列表blacklist,其中blacklist中的元素在[0,N)范围内,调用pick方法的时候随机返回一个数,这个数满足

  1. 在[0,N)范围
  2. 不在blacklist内
  3. 要随机

思路:构造一个集合M,该M是 [0,N) - blacklist 的一个集合,调用pick时,返回[0,M)的一个随机数并根据这个随机数从集合M中取数即可。

Java实现:

class Solution {
    int M;
    Map<Integer, Integer> map;
    Random r;
    public Solution(int N, int[] blacklist) {
        M = N - blacklist.length;
        map = new HashMap<>();
        r = new Random();
        for (int tmp : blacklist) {
            map.put(tmp, -1);
        }
        
        for (int tmp : blacklist) {
            if (tmp < M) {
                while (map.containsKey(N-1)) {
                    N--;
                }
                map.put(tmp, --N);
            }
        }
    }

    public int pick() {
        // random in [0,N) not in blacklist
        int p = r.nextInt(M);
        if (map.containsKey(p)) return map.get(p);
        return p;
    }
}

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

以上是关于710. Random Pick with Blacklist - LeetCode的主要内容,如果未能解决你的问题,请参考以下文章

528. Random Pick with Weight

528. Random Pick with Weight

leetcode 528. Random Pick with Weight

[LeetCode] Random Pick with Weight 根据权重随机取点

[leetcode]528. Random Pick with Weight按权重挑选索引

[LeetCode] Random Pick with Blacklist 带黑名单的随机选取