-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertDeleteGetRandom.ts
More file actions
60 lines (46 loc) · 1.25 KB
/
Copy pathinsertDeleteGetRandom.ts
File metadata and controls
60 lines (46 loc) · 1.25 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* Solve this with O(n) space and O(1) time
*/
class RandomizedSet {
valueMap: Map<number, number>;
valueArray: Array<number>;
constructor() {
this.valueMap = new Map();
this.valueArray = [];
}
insert(val: number): boolean {
const foundValue = this.valueMap.has(val);
if (foundValue) {
return false;
}
this.valueMap.set(val, this.valueArray.length);
this.valueArray.push(val);
return true;
}
remove(val: number): boolean {
const foundValue = this.valueMap.has(val);
if (!foundValue) {
return false;
}
const removeIndex = this.valueMap.get(val);
this.valueMap.delete(val);
this.valueArray[removeIndex] = this.valueArray[this.valueArray.length - 1];
this.valueArray.pop();
this.valueMap.set(this.valueArray[removeIndex], removeIndex);
return true;
}
getRandom(): number {
const randomIndex = Math.floor(Math.random() * this.valueArray.length);
return this.valueArray[randomIndex];
}
}
/**
* 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()
*/
const randomizedSet = new RandomizedSet();
console.log(randomizedSet.insert(1));
console.log(randomizedSet.remove(0));