Skip to content

Commit dce7ea1

Browse files
committed
feat: leetcode 710
1 parent ff21aa7 commit dce7ea1

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

problemset/random-pick-with-blacklist/README.md

+39
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,43 @@ solution.pick(); // 返回 6
3535
solution.pick(); // 返回 1
3636
solution.pick(); // 返回 0
3737
solution.pick(); // 返回 4
38+
```
39+
40+
## 解题
41+
42+
```ts
43+
/**
44+
* 黑名单映射
45+
*/
46+
export class Solution {
47+
bound: number
48+
b2w: Map<number, number>
49+
50+
constructor(n: number, blacklist: number[]) {
51+
this.b2w = new Map<number, number>()
52+
const len = blacklist.length
53+
this.bound = n - len
54+
const black = new Set()
55+
56+
for (const b of blacklist) {
57+
if (b >= this.bound)
58+
black.add(b)
59+
}
60+
61+
let w = this.bound
62+
for (const b of blacklist) {
63+
if (b < this.bound) {
64+
while (black.has(w)) w++
65+
66+
this.b2w.set(b, w)
67+
w++
68+
}
69+
}
70+
}
71+
72+
pick(): number {
73+
const x = Math.floor(Math.random() * this.bound)
74+
return this.b2w.get(x) || x
75+
}
76+
}
3877
```

problemset/random-pick-with-blacklist/index.ts

+3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
/**
2+
* 黑名单映射
3+
*/
14
export class Solution {
25
bound: number
36
b2w: Map<number, number>

0 commit comments

Comments
 (0)