forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.ts
39 lines (34 loc) · 944 Bytes
/
Solution.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class RandomizedSet {
private d: Map<number, number> = new Map();
private q: number[] = [];
constructor() {}
insert(val: number): boolean {
if (this.d.has(val)) {
return false;
}
this.d.set(val, this.q.length);
this.q.push(val);
return true;
}
remove(val: number): boolean {
if (!this.d.has(val)) {
return false;
}
const i = this.d.get(val)!;
this.d.set(this.q[this.q.length - 1], i);
this.q[i] = this.q[this.q.length - 1];
this.q.pop();
this.d.delete(val);
return true;
}
getRandom(): number {
return this.q[Math.floor(Math.random() * this.q.length)];
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* var obj = new RandomizedSet()
* var param_1 = obj.insert(val)
* var param_2 = obj.remove(val)
* var param_3 = obj.getRandom()
*/