😎풀이

  1. 초기화 시 인자 nums를 순회하며, 요소를 key로 갖는 각 인덱스 저장
  2. pick 호출 시, target에 해당하는 인덱스를 중 랜덤한 인덱스를 반환
class Solution {
    private map: Map<number, number[]>
    constructor(nums: number[]) {
        const map = new Map()
        for(let i = 0; i < nums.length; i++) {
            map.set(nums[i], [...(map.get(nums[i]) ?? []), i])
        }
        this.map = map
    }

    pick(target: number): number {
        const indexies = this.map.get(target)
        const rand = Math.floor(Math.random() * indexies.length)
        return indexies[rand]
    }
}
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글