File tree 2 files changed +42
-0
lines changed
problemset/random-pick-with-blacklist
2 files changed +42
-0
lines changed Original file line number Diff line number Diff line change @@ -35,4 +35,43 @@ solution.pick(); // 返回 6
35
35
solution.pick(); // 返回 1
36
36
solution.pick(); // 返回 0
37
37
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
+ }
38
77
```
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 黑名单映射
3
+ */
1
4
export class Solution {
2
5
bound : number
3
6
b2w : Map < number , number >
You can’t perform that action at this time.
0 commit comments