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().

Note:

  1. 1 <= N <= 1000000000
  2. 0 <= B.length < min(100000, N)
  3. [0, N) does NOT include N. See interval notation.

Example 1:

Input:
["Solution","pick","pick","pick"]
[[1,[]],[],[],[]]
Output: [null,0,0,0]

Example 2:

Input:
["Solution","pick","pick","pick"]
[[2,[]],[],[],[]]
Output: [null,1,1,1]

Example 3:

Input:
["Solution","pick","pick","pick"]
[[3,[1]],[],[],[]]
Output: [null,0,0,2]

Example 4:

Input:
["Solution","pick","pick","pick"]
[[4,[2]],[],[],[]]
Output: [null,1,3,1]

Explanation of Input Syntax:

The input is two lists: the subroutines called and their arguments. Solution's constructor has two arguments, N and the blacklist Bpick has no arguments. Arguments are always wrapped with a list, even if there aren't any.

这道题让我们生成一个N以内的随机数,但是还给了一个黑名单,意思是黑名单里面的数字不能被选到。于是博主最先想到的方法就是用拒绝采样Rejection Sampling来做,因为之前做过使用该方法的两道题 Implement Rand10() Using Rand7() 和 Generate Random Point in a Circle,所以可以立马想到。思路其实很简单,就是随机一个数,如果是黑名单里的,那么就重新随机。为了提高在黑名单中查找数字的速度,我们将所有黑名单的数字放到一个HashSet中,这样我们就拥有了常数级查找的速度,看似一切水到渠成,燃鹅被OJ强行打脸,TLE!那么换一种思路吧,既然你有黑名单,那么林北就有白名单,把所有没被block的数字都放到一个新数组中,然后随机生成数组坐标不就完了。燃鹅x2,又被OJ放倒了,MLE!不准用这么多内存。岂可修,真的没别的办法了嘛?!还好方法解答贴中给了一种使用HashMap的方法来做,博主仔细研读了一番,发现确实秒啊!既然数字总共有N个,那么减去黑名单中数字的个数,就是最多能随机出来的个数。比如N=5,黑名单中有两个数{2, 4},那么我们最多只能随机出三个,但是我们如果直接rand()%3,会得到0,1,2,我们发现有两个问题,一是黑名单中的2可以随机到,二是数字3没法随机到。那么我们想,能不能随机到0或1则返回其本身,而当随机到2到时候,我们返回的是3,我们需要建立这样的映射,这就是使用HashMap的动机啦。我们首先将超过N - blacklist.size()的数字放入一个HashSet,这里就把{3, 4}放进去了,然后我们遍历blacklist中的数字,如果在HashSet中的话,就将其删除,这样HashSet中就只有{3}了,这个需要建立映射的数字,而用什么数字建立,当然是用黑名单中的数字了,遍历黑名单中的数字,如果小于N - blacklist.size()的话,说明是有可能随机到的,我们和HashSet中的第一个数字建立映射,然后我们可以用个iterator,指向HashSet中的下一个数组,然后继续建立映射。从而实现在pick函数中的移魂换影大法了,先随机个数字,如果有映射,则返回映射值,否则返回原数字,参见代码如下:

class Solution {
public:
Solution(int N, vector<int> blacklist) {
unordered_set<int> st;
len = N - blacklist.size();
for (int i = len; i < N; ++i) st.insert(i);
for (int num : blacklist) st.erase(num);
auto it = st.begin();
for (int num : blacklist) {
if (num < len) m[num] = *it++;
}
} int pick() {
int k = rand() % len;
return m.count(k) ? m[k] : k;
} private:
unordered_map<int, int> m;
int len;
};

类似题目:

Random Pick with Weight

Random Pick Index

参考资料:

https://leetcode.com/problems/random-pick-with-blacklist/

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Random Pick with Blacklist 带黑名单的随机选取的更多相关文章

  1. 710. Random Pick with Blacklist - LeetCode

    Question 710. Random Pick with Blacklist Solution 题目大意:给一个N,表示一个范围[0,N),给一个黑名单列表blacklist,其中blacklis ...

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

    Given an array w of positive integers, where w[i] describes the weight of index i, write a function  ...

  3. [Swift]LeetCode710. 黑名单中的随机数 | Random Pick with Blacklist

    Given a blacklist B containing unique integers from [0, N), write a function to return a uniform ran ...

  4. 710 Random Pick with Blacklist

    1. 问题 给定一个黑名单,包含[0, N)的一些数,从[0, N)之间的非黑名单数中随机采样一个值. 2. 思路 字典映射 (1)计算黑名单数的长度,记作B,因为已经排除掉了B个元素,所以最后是从N ...

  5. [LeetCode] Random Pick Index 随机拾取序列

    Given an array of integers with possible duplicates, randomly output the index of a given target num ...

  6. Leetcode: Random Pick Index

    Given an array of integers with possible duplicates, randomly output the index of a given target num ...

  7. LeetCode 528. Random Pick with Weight

    原题链接在这里:https://leetcode.com/problems/random-pick-with-weight/ 题目: Given an array w of positive inte ...

  8. 398. Random Pick Index - LeetCode

    Question 398. Random Pick Index Solution 思路:重点是如果数据中有多个数target相等,要从这些数中随机取一个,根据例题 假设输入是: int[] nums ...

  9. [LeetCode] Random Point in Non-overlapping Rectangles 非重叠矩形中的随机点

    Given a list of non-overlapping axis-aligned rectangles rects, write a function pick which randomly ...

随机推荐

  1. 第十五节:Expression表达式目录树(与委托的区别、自行拼接、总结几类实例间的拷贝)

    一. 基本介绍 回忆: 最早接触到表达式目录树(Expression)可能要追溯到几年前使用EF早期的时候,发现where方法里的参数是Expression<Func<T,bool> ...

  2. 玩转ubuntu之初体验

    安装的是ubuntu16.04.1,分区和具体细节就不多说了,非常简单 安装完之后要做的几件事: 1.设置root密码 #设置root密码 sudo passwd root 2.检查并更新系统 #ub ...

  3. webpack安装异常

    webpack中文指南:https://zhaoda.net/webpack-handbook/index.html 今天中午,我用   cnpm install   重新下载了一下项目的依赖,爆了一 ...

  4. 401 experience

    AM: 块元素与内联元素  : div与span的区别 span只能设置水平的margin(左右内外边距) 在span里面加 display:block; 内联转块(相当于给span加了上下的边距)反 ...

  5. 双系统下Ubuntu扩展根目录空间方法

    最近,在Ubuntu16.04上装了个matlab,突然发现根目录空间只剩1G了,这哪儿够用啊,就想着有没有一种方法不用重装系统就可以扩展根目录空间呢?别说还真有,看下文. 开始之前先分出一些未分配空 ...

  6. PHP 【一】

    输出    [输出在表格中] <!DOCTYPE html> <html> <body> <h1>My first PHP page</h1> ...

  7. torch.linspace,unsqueeze()以及squeeze()函数

    1.torch.linspace(start,end,steps=100,dtype) 作用是返回一个一维的tensor(张量),其中dtype是返回的数据类型. import torch print ...

  8. linux服务器安装Mysql后,只能看到information_schema/test这两个库,无法修改密码

    参考链接:https://www.cnblogs.com/ThinkVenus/p/7670722.html 问题背景:登录mysql失败,密码错误,由此想到需要更改密码 然而,进入数据库后,只能看到 ...

  9. canvas图片与img图片的相互转换

    最近在一个项目中,遇到了一个问题,需要把生成的canvas形式的二维码转换为图片,可以长按识别,保存等.查找了一些资料归纳总结了一些知识. 默认在jq库里进行,引入jquery.qrcode.min. ...

  10. 参数ref与out

    通常我们向方法中传递的是值,方法获得的是这些值的一个拷贝,然后使用这些拷贝,当方法运行完毕后,这些拷贝将被丢弃,而原来的值不会受到影响. 这种情况是通常的,当然还有另外一种情况,我们向方法传递参数的形 ...