43-Linked List Random Node

题目地址:Linked List Random Node
Given a singly linked list, return a random node’s value from the linked list. Each node must have the same probability of being chosen.
Follow up:
What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?
Example:
// Init a singly linked list [1,2,3].
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
Solution solution = new Solution(head);
// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
solution.getRandom();

import java.util.Random;

/**
 *原链接:http://bookshadow.com/weblog/2016/08/10/leetcode-linked-list-random-node/
 * 数学归纳法:https://www.cnblogs.com/wanghai0666/p/5867174.html
 * 蓄水池抽样(Reservoir Sampling)
 * 蓄水池抽样算法的等概率性可以用数学归纳法证明:
 * 一:当count等于1,抽出第1个的概率是1;
 * 二:当count等于2,抽中第二个的概率是1/2;
 * 三:假设抽取前k个元素的概率相等,均为1/k;
 * 四:当抽取第k+1个元素时:
若0到k的可能性等于0,则返回值为第n+1个元素,其概率为1/(n+1);
否则,抽取的依然是前n个元素,其概率为1/n * n/(n+1) = 1/(n+1)
 */
public class LinkedListRandomNode {
    private ListNode node;
    Random random;

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

    public int getRandom() {
        int count = 1;
        int res = node.val;
        while (node.next != null) {
            node = node.next;
            if (random.nextInt(count + 1) == count) {
                res = node.val;
            }
            count++;
        }
        return res;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        LinkedListRandomNode solution = new LinkedListRandomNode(head);
        System.out.println(solution.getRandom());
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值