Skip to content

Instantly share code, notes, and snippets.

@yevmoroz
Created April 16, 2024 00:11
Show Gist options
  • Save yevmoroz/af5f26da62ff2fa909d4c14c4794750d to your computer and use it in GitHub Desktop.
Save yevmoroz/af5f26da62ff2fa909d4c14c4794750d to your computer and use it in GitHub Desktop.
leetcode randset
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