对于每个 [0,n-m) 范围内的黑名单数 b,首先不断增加 w 直至其不在黑名单中,然后将 b 映射到 w 上,并将 w 增加一。
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: def__init__(self, n: int, blacklist: List[int]): m = len(blacklist) self.bound = w = n - m black = {b for b in blacklist if b >= self.bound} self.b2w = {} for b in blacklist: if b < self.bound: while w in black: w += 1 self.b2w[b] = w w += 1
defpick(self) -> int: x = randrange(self.bound) return self.b2w.get(x, x)
classSolution { unordered_map<int, int> b2w; int bound;
public: Solution(int n, vector<int> &blacklist) { int m = blacklist.size(); bound = n - m; unordered_set<int> black; for (int b: blacklist) { if (b >= bound) { black.emplace(b); } }
int w = bound; for (int b: blacklist) { if (b < bound) { while (black.count(w)) { ++w; } b2w[b] = w++; } } }
intpick(){ int x = rand() % bound; return b2w.count(x) ? b2w[x] : x; } };
classSolution { Map<Integer, Integer> b2w; Random random; int bound;
publicSolution(int n, int[] blacklist) { b2w = newHashMap<Integer, Integer>(); random = newRandom(); intm= blacklist.length; bound = n - m; Set<Integer> black = newHashSet<Integer>(); for (int b : blacklist) { if (b >= bound) { black.add(b); } }
intw= bound; for (int b : blacklist) { if (b < bound) { while (black.contains(w)) { ++w; } b2w.put(b, w); ++w; } } }
publicclassSolution { Dictionary<int, int> b2w; Random random; int bound;
publicSolution(int n, int[] blacklist) { b2w = new Dictionary<int, int>(); random = new Random(); int m = blacklist.Length; bound = n - m; ISet<int> black = new HashSet<int>(); foreach (int b in blacklist) { if (b >= bound) { black.Add(b); } }
int w = bound; foreach (int b in blacklist) { if (b < bound) { while (black.Contains(w)) { ++w; } b2w.Add(b, w); ++w; } } }
publicintPick() { int x = random.Next(bound); return b2w.ContainsKey(x) ? b2w[x] : x; } }
type Solution struct { b2w map[int]int bound int }
funcConstructor(n int, blacklist []int) Solution { m := len(blacklist) bound := n - m black := map[int]bool{} for _, b := range blacklist { if b >= bound { black[b] = true } }
b2w := make(map[int]int, m-len(black)) w := bound for _, b := range blacklist { if b < bound { for black[w] { w++ } b2w[b] = w w++ } } return Solution{b2w, bound} }
func(s *Solution) Pick() int { x := rand.Intn(s.bound) if s.b2w[x] > 0 { return s.b2w[x] } return x }
varSolution = function(n, blacklist) { this.b2w = newMap(); const m = blacklist.length; this.bound = n - m; const black = newSet(); for (const b of blacklist) { if (b >= this.bound) { black.add(b); } }
let w = this.bound; for (const b of blacklist) { if (b < this.bound) { while (black.has(w)) { ++w; } this.b2w.set(b, w); ++w; } } };