当前位置:网站首页>leetcode:710. 黑名单中的随机数【映射思维】
leetcode:710. 黑名单中的随机数【映射思维】
2022-06-26 21:38:00 【白速龙王的回眸】

分析
我们先给一个界限bound 我们希望所有黑名单都可以映射到bound(包括)之后的位置
如果黑名单本来就在bound后面,我们直接把它放入black中
然后遍历其余黑名单,如果发现,它在bound前面
我们从bound的值开始,开始逐个往后遍历,找到第一个非黑名单的位置w
然后令b2w[b] = w这样就完成了黑名单到白名单的映射
然后最后使用随机出一个[0, bound - 1]的数
如果没有映射,说明它就是白名单;如果有隐射,找到其对应的白名单即可
ac code
class Solution:
def __init__(self, n: int, blacklist: List[int]):
m = len(blacklist)
self.bound = w = n - m
# 假设bound后面都是黑名单,前面都是白名单
black = {
b for b in blacklist if b >= self.bound}
self.b2w = {
}
for b in blacklist:
# 如果前面遇到黑名单
if b < self.bound:
# 找到后面中的空位
while w in black:
w += 1
# 把当前的黑名单 映射 给 对应位置的白名单
self.b2w[b] = w
# 下一个位置
w += 1
#print(self.b2w)
def pick(self) -> int:
x = randrange(self.bound) # 不含右端点,从0开始,步长为1
#x = randint(0, self.bound - 1)
return self.b2w.get(x, x) # 如果不是黑名单,就选自己;否则选映射的白名单
总结
黑名单映射的方法,使得按照前bound个随机的情况下
能找到黑名单映射的白名单的值即可
边栏推荐
- 360手机助手首家接入APP签名服务系统 助力隐私安全分发
- Twenty five of offer - all paths with a certain value in the binary tree
- Treasure and niche cover PBR multi-channel mapping material website sharing
- [Bayesian classification 3] semi naive Bayesian classifier
- random_ normal_ Initializer uses
- 基于QT实现简单的连连看小游戏
- [Shandong University] information sharing for the first and second examinations of postgraduate entrance examination
- QT based "synthetic watermelon" game
- 诗尼曼家居冲刺A股:年营收近12亿 红星美凯龙与居然之家是股东
- 聊聊我的远程工作体验 | 社区征文
猜你喜欢

The postgraduate entrance examination in these areas is crazy! Which area has the largest number of candidates?

Web crawler 2: crawl the user ID and home page address of Netease cloud music reviews

VB.net类库——4给屏幕截图,裁剪

In 2022, where will the medium and light-weight games go?

12个MySQL慢查询的原因分析

【protobuf 】protobuf 昇級後帶來的一些坑

BN(Batch Normalization) 的理论理解以及在tf.keras中的实际应用和总结

传纸条【动态规划】

CVPR 2022 | 美团技术团队精选论文解读

What are the accounting elements
随机推荐
Which securities company is the most convenient, safe and reliable for opening an account
leetcode刷题:字符串05(剑指 Offer 58 - II. 左旋转字符串)
记录一次Redis大Key的排查
基于QT实现简单的连连看小游戏
[Shandong University] information sharing for the first and second examinations of postgraduate entrance examination
Leetcode(452)——用最少数量的箭引爆气球
Application and Optimization Practice of 100 million level monthly live national karaoke feed service in Tencent cloud mongodb
leetcode刷题:字符串06(实现 strStr())
Gamefi active users, transaction volume, financing amount and new projects continue to decline. Can axie and stepn get rid of the death spiral? Where is the chain tour?
网络连接断开请刷新重试
Leetcode question brushing: String 03 (Sword finger offer 05. replace space)
第2章 构建自定义语料库
VB.net类库——4给屏幕截图,裁剪
线性模型LN、单神经网络SNN、深度神经网络DNN与CNN测试对比
网络爬虫终篇:向10万级网易云用户发送定向消息
【 protobuf 】 quelques puits causés par la mise à niveau de protobuf
Many gravel 3D material mapping materials can be obtained with one click
MATLAB与Mysql数据库连接并数据交换(基于ODBC)
Can compass open an account for stock trading? Is it safe?
指南针能开户炒股吗?安全吗?