Leetcode - Linked List Random Node

My code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    ListNode head = null;
    ListNode result = null;
    Random r;
    /** @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) {
        this.head = head;
        r = new Random();
    }
    
    /** Returns a random node's value. */
    public int getRandom() {
        ListNode curr = head;
        int i = 1;
        while (curr != null) {
            if (r.nextInt(i) == 0) {
                result = curr;
            }
            i++;
            curr = curr.next;
        }
        
        return result.val;
    }
}

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(head);
 * int param_1 = obj.getRandom();
 */

reference:
what is reservoir sampling:
https://en.wikipedia.org/wiki/Reservoir_sampling

https://discuss.leetcode.com/topic/53738/o-n-time-o-1-space-java-solution

一开始并不清楚 reservoir sampling的做法,这下清楚了,就好写了。
主要用于,当我们需要随机取样,但是又不知道这个序列长度到底多少时,如何保证概率的平均分布。
time complexity: O(n)
space complexity: O(1)

Anyway, Good luck, Richardo! — 10/12/0216

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/97966f220772
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞