给定一个整数 n 和一个 无重复 黑名单整数数组 blacklist 。设计一种算法,从 [0, n - 1] 范围内的任意整数中选取一个 未加入 黑名单 blacklist 的整数。任何在上述范围内且不在黑名单 blacklist 中的整数都应该有 同等的可能性 被返回。
优化你的算法,使它最小化调用语言 内置 随机函数的次数。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/random-pick-with-blacklist
解题思路:
用bound来表示需要随机的数量的最大边界,大于这个边界的黑名单数不管,小于这个边界的黑名单数与大于其边界的正常数实现一个Map映射。
代码如下:
class Solution {
Map<Integer,Integer> ans;
Random random;
int bound;
public Solution(int n, int[] blacklist) {
ans=new HashMap<Integer,Integer>();
random=new Random();
int m=blacklist.length;
bound=n-m;
Set<Integer> black=new HashSet<Integer>();
for(int b:blacklist){
if(b>=bound){
black.add(b);
}
}
int w=bound;
for(int b:blacklist){
if(b<bound){
while(black.contains(w)){
w++;
}
ans.put(b,w);
w++;
}
}
}
public int pick() {
int x=random.nextInt(bound);
return ans.getOrDefault(x,x);
}
}