Created
April 16, 2024 00:11
-
-
Save yevmoroz/af5f26da62ff2fa909d4c14c4794750d to your computer and use it in GitHub Desktop.
leetcode randset
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RandomizedSet { | |
constructor() { | |
this.set = new Map(); | |
this.array = []; | |
} | |
insert(val) { | |
if (this.set.has(val)) { | |
return false; | |
} | |
this.array.push(val); | |
this.set.set(val, this.array.length - 1); | |
return true; | |
} | |
remove(val) { | |
if (!this.set.has(val)) { | |
return false; | |
} | |
const indexToRemove = this.set.get(val); | |
const lastIndex = this.array.length - 1; | |
[this.array[indexToRemove], this.array[lastIndex]] = [this.array[lastIndex], this.array[indexToRemove]]; | |
this.set.set(this.array[indexToRemove], indexToRemove); | |
this.array.pop(); | |
this.set.delete(val); | |
return true; | |
} | |
getRandom() { | |
const randomIndex = Math.floor(Math.random() * this.array.length); | |
return this.array[randomIndex]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment