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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 上班路上听罗辑思维讲到博物学精神,于是把刘华杰2014年的一席演讲《博物学生存》又重温了一遍,他提及一句梅特林克写...
    顾左盼右阅读 3,785评论 0 3

友情链接更多精彩内容