710. 黑名单中的随机数
给定一个整数 n 和一个 无重复 黑名单整数数组 blacklist 。设计一种算法,从 [0, n - 1] 范围内的任意整数中选取一个 未加入 黑名单 blacklist 的整数。任何在上述范围内且不在黑名单 blacklist 中的整数都应该有 同等的可能性 被返回。
优化你的算法,使它最小化调用语言 内置 随机函数的次数。
实现 Solution 类:
Solution(int n, int[] blacklist) 初始化整数 n 和被加入黑名单 blacklist 的整数
int pick() 返回一个范围为 [0, n - 1] 且不在黑名单 blacklist 中的随机整数
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/random-pick-with-blacklist
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.HashMap;
import java.util.Map;
class Solution {
private int size;
private Map<Integer, Integer> blackMap = new HashMap<>();
public Solution(int n, int[] blacklist) {
for (int black : blacklist) {
blackMap.put(black, null);
}
size = n - blacklist.length;
int last = n - 1;
for (int black : blacklist) {
if (black >= size) {
continue;
}
while (blackMap.containsKey(last)) {
last--;
}
blackMap.put(black, last--);
}
}
public int pick() {
int index = (int) (Math.random() * size);
Integer num = blackMap.get(index);
return num != null ? num : index;
// int index = (int) (Math.random() * size);
// if (blackMap.containsKey(index)) {
// return blackMap.get(index);
// }
// return index;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(n, blacklist);
* int param_1 = obj.pick();
*/
心之所向,素履以往 生如逆旅,一苇以航