Bootstrap

Java | Leetcode Java题解之第382题链表随机节点

题目:

题解:

class Solution {
    ListNode head;
    Random random;

    public Solution(ListNode head) {
        this.head = head;
        random = new Random();
    }

    public int getRandom() {
        int i = 1, ans = 0;
        for (ListNode node = head; node != null; node = node.next) {
            if (random.nextInt(i) == 0) { // 1/i 的概率选中(替换为答案)
                ans = node.val;
            }
            ++i;
        }
        return ans;
    }
}
;