710. Random Pick with Blacklist - LeetCode
Question
710. Random Pick with Blacklist
Solution
题目大意:给一个N,表示一个范围[0,N),给一个黑名单列表blacklist,其中blacklist中的元素在[0,N)范围内,调用pick方法的时候随机返回一个数,这个数满足
- 在[0,N)范围
- 不在blacklist内
- 要随机
思路:构造一个集合M,该M是 [0,N) - blacklist 的一个集合,调用pick时,返回[0,M)的一个随机数并根据这个随机数从集合M中取数即可。
Java实现:
class Solution {
int M;
Map<Integer, Integer> map;
Random r;
public Solution(int N, int[] blacklist) {
M = N - blacklist.length;
map = new HashMap<>();
r = new Random();
for (int tmp : blacklist) {
map.put(tmp, -1);
}
for (int tmp : blacklist) {
if (tmp < M) {
while (map.containsKey(N-1)) {
N--;
}
map.put(tmp, --N);
}
}
}
public int pick() {
// random in [0,N) not in blacklist
int p = r.nextInt(M);
if (map.containsKey(p)) return map.get(p);
return p;
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(N, blacklist);
* int param_1 = obj.pick();
*/