class Solution {
int count;
HashMap<Integer, Integer> map;
Random random;
public Solution(int N, int[] blacklist) {
random = new Random();
map = new HashMap<>();
for (int b : blacklist) {
// 此处 value 任意赋值,key 占位
map.put(b, -1);
}
// 除去黑名单元素个数的最终元素个数
count = N - map.size();
// 最后一个元素的下标索引
int last = N - 1;
// 将黑名单中元素的索引映射到最后去
for (int b : blacklist) {
// b 如果在区间 [count, N) ,直接忽略
if (b >= count) {
continue;
}
while (map.containsKey(last)) {
last--;
}
map.put(b, last);
last--;
}
}
public int pick() {
// 随机选取下标
int index = random.nextInt(count);
// 如果命中黑名单元素对应的索引,映射到其他索引
if (map.containsKey(index)) {
return map.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();
*/