LeetCode: Linked List Random Node

이원희·2020년 12월 3일
0

📝 PS

목록 보기
17/65
post-thumbnail

아... 시간 맞춰서 풀었는데 외국 시간 기준이라서 12시간 넘었다.... 그래서 안 푼거로 되었다...^^
시간 잘 보고 풀어야지..

랜덤하게 ListNode의 값을 return해주는 문제였다.
랜덤하지만 공평한? 확률로 return해줘야 한다.

import java.util.*;
class Solution {

    Random r = null;
    ListNode h = null;
    
    /** @param head The linked list's head.
        Note that the head is guaranteed to be not null, so it contains at least one node. */
    public Solution(ListNode head) {
        r = new Random();
        h = head;
    }
    
    /** Returns a random node's value. */
    public int getRandom() {
        int count=1;
        ListNode p = h;
        int result = 0;
        while(p!=null){
            if(r.nextInt(count)==0)
                result= p.val;
            count++;
            p = p.next;
        }
        return result;
    }
}

0개의 댓글