
😎풀이
- Set 자료구조 생성
- 값이 추가 될 경우 기존에 해당 값이 존재하지 않았다면
true, 존재했다면 false 반환
- 값이 제거 될 경우 기존에 해당 값이 존재했다면
true, 존재하지 않았다면 false 반환
- 랜덤 값은 현재 존재하는 요소 중 랜덤한 인덱스의 값 반환
class RandomizedSet {
private set: Set<number>
constructor() {
this.set = new Set<number>()
}
insert(val: number): boolean {
const hasItem = this.set.has(val)
this.set.add(val)
return !hasItem
}
remove(val: number): boolean {
const hasItem = this.set.has(val)
this.set.delete(val)
return hasItem
}
getRandom(): number {
const size = this.set.size
const randomIdx = Math.floor(Math.random() * size)
return Array.from(this.set)[randomIdx]
}
}