当前位置:网站首页>力扣 710. 黑名单中的随机数
力扣 710. 黑名单中的随机数
2022-07-01 21:56:00 【三更鬼】
题目来源:https://leetcode.cn/problems/random-pick-with-blacklist/
大致题意:
给定一个数字范围 n,一个黑名单数组,设计一个类返回 0 到 n - 1 之间不在黑名单中的随机数,要求每个数被返回的概率应该相等
思路
设黑名单数组长度为 m,那么返回数字的个数有 n - m 个
所以可以设置随机数的 bound 为 n - m
- 若黑名单中的数都大于等于 bound,那么不用做任何处理
- 若黑名单中的数有小于 bound,可以使用哈希表将其映射到 [bound, n - 1] 中。这样在随机数生成器生成黑名单中小于 bound 的数时,直接映射到另一个数即可
代码:
public class Pick {
// 映射黑名单小于 bound 的数
Map<Integer, Integer> map;
int bound;
Random random;
public Pick(int n, int[] blacklist) {
map = new HashMap<>();
int m = blacklist.length;
// 初始化 bound
bound = n - m;
random = new Random();
// 存黑名单数字的哈希表
Set<Integer> blackSet = new HashSet<>();
for (int num : blacklist) {
if (num >= bound) {
blackSet.add(num);
}
}
// 映射索引
int idx = bound;
// 遍历黑名单
for (int num : blacklist) {
// 若该黑名单数字小于 bound,将其映射为 [bound, n - 1] 中不在黑名单且还未被映射的数
if (num < bound) {
// 若当前要映射的数在黑名单中,索引 +1
while (blackSet.contains(idx)) {
idx++;
}
map.put(num, idx++);
}
}
}
public int pick() {
// 生成随机数
int x = random.nextInt(bound);
// 返回随机数,若随机数在 map 中,返回其映射的数字
return map.getOrDefault(x, x);
}
}
边栏推荐
- Pytorch's code for visualizing feature maps after training its own network
- "Trust machine" empowers development
- vSphere+、vSAN+来了!VMware 混合云聚焦:原生、快速迁移、混合负载
- Kubernetes创建Service访问Pod
- Friendly serial assistant tutorial_ How to configure friendly serial port debugging assistant - tutorial on using friendly serial port debugging assistant
- 搜狗微信APP逆向(二)so层
- mixconv代码
- Yolov5.5 call local camera
- Single step debugging analysis of rxjs observable of operator
- 陈天奇的机器学习编译课(免费)
猜你喜欢
切面条 C语言
I graduated from college in 14 years and changed to software testing in 3 months. My monthly salary was 13.5k. At the age of 32, I finally found the right direction
转--原来gdb的底层调试原理这么简单
MySQL -- index of MyISAM storage engine
“信任机器”为发展赋能
Understanding of transactions in MySQL
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received
Hide the creation and use of users
转--深入LUA脚本语言,让你彻底明白调试原理
内部字段分隔符
随机推荐
[image segmentation] 2021 segformer neurips
nn.Parameter】Pytorch特征融合自适应权重设置(可学习权重使用)
el-input文本域字数限制,超过显示变红并禁止输入
Resttemplate remote call tool class
447 Bili Bili noodles warp 1
分享一个一年经历两次裁员的程序员的一些感触
每日刷题记录 (十)
Cutefishos system~
下班前几分钟,我弄清了v-model与.sync的区别
MySQL view exercise
cvpr2022 human pose estiamtion
ECMAScript 2022 正式发布,有你了解过的吗?
The fixed assets management subsystem reports are divided into what categories and which accounts are included
多图预警~ 华为 ECS 与 阿里云 ECS 对比实战
[QT widget] encapsulates a simple thread management class
台积电全球员工薪酬中位数约46万,CEO约899万;苹果上调日本的 iPhone 售价 ;Vim 9.0 发布|极客头条
正则系列之组和范围(Groups and Ranges)
陈天奇的机器学习编译课(免费)
Understanding of inverted residuals
cvpr2022 human pose estiamtion