[LeetCode] 382. Linked List Random Node

Chobby·2026년 1월 29일

LeetCode

목록 보기
976/992

😎풀이

  1. head를 입력받아 ListNode의 크기를 탐색
  2. getRandom이 호출될 경우, 크기 내에 랜덤한 숫자의 노드 값 반환
class Solution {
    private head: ListNode | null
    private size: number
    constructor(head: ListNode | null) {
        this.head = head
        let point = head
        let size = 1
        while(point.next) {
            size++
            point = point.next
        }
        this.size = size
    }

    getRandom(): number {
        let point = this.head
        const randomIdx = Math.floor(Math.random() * this.size)
        for(let i = 0; i < randomIdx; i++) {
            point = point.next
        }
        return point.val
    }
}
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글