当前位置:网站首页>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个随机的情况下
能找到黑名单映射的白名单的值即可
边栏推荐
猜你喜欢

基于Qt实现的“合成大西瓜”小游戏

360 mobile assistant is the first to access the app signature service system to help distribute privacy and security

Matrix calculator design for beginners of linear algebra based on Qt development

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?
![[serial] shuotou O & M monitoring system 01 overview of monitoring system](/img/b2/bc75a4d0c8d98056d93ba99b3e6193.png)
[serial] shuotou O & M monitoring system 01 overview of monitoring system

Leetcode question brushing: String 05 (Sword finger offer 58 - ii. left rotation string)

Leetcode(763)——划分字母区间

Many gravel 3D material mapping materials can be obtained with one click

线性模型LN、单神经网络SNN、深度神经网络DNN与CNN测试对比

Redis + Guava 本地缓存 API 组合,性能炸裂!
随机推荐
Hands on deep learning pytorch version 3 - Data Preprocessing
不同的子序列问题I
numpy中mgrid的用法
DAST black box vulnerability scanner part 5: vulnerability scanning engine and service capability
不要做巨婴了
股票炒股注册开户有没有什么风险?安全吗?
[Shandong University] information sharing for the first and second examinations of postgraduate entrance examination
[Bayesian classification 2] naive Bayesian classifier
Listing of maolaiguang discipline on the Innovation Board: it is planned to raise 400million yuan. Fanyi and fanhao brothers are the actual controllers
Introduction of classic wide & deep model and implementation of tensorflow 2 code
VB.net类库,获取屏幕内鼠标下的颜色(进阶——3)
网络爬虫终篇:向10万级网易云用户发送定向消息
Common concurrent testing tools and pressure testing methods
基于启发式搜索的一字棋
[leetcode]- linked list-2
How to analyze financial expenses
Usage of MGrid in numpy
「连续学习Continual learning, CL」最新2022研究综述
2022年,中轻度游戏出海路在何方?
Establish a connection with MySQL