Leetcode382:Linked List Random Node

本文介绍了一种算法,用于从链表中随机选择一个节点,确保每个节点被选中的概率相同。通过逐步增加随机数范围,每次迭代都有机会更新当前选中的节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目要求:给定一个链表,随机输出链表中的一个数,要求每个数输出的概率相等。

思路: 可以先计算出链表长度, 然后随机一个在长度范围内的值, 走到那里将值返回即可. 但是如果长度无限大, 就无法计算长度了, 这种情况下用一个水池抽样的算法, 其原理为一个个的对元素取样, 在遍历到每个元素的时候可以有个概率选取, 或者不选取。

具体:1、初始答案为第一个数,此时链表的下标指向第一个数,即此时第一个数被选中的概率为1;

           2、下标后移一位指向第二个数,用Random函数随机抽取0-1的数,抽取的范围是2,抽中1的概率为1/2,如果抽中1,把答案改为此时下标所指的数,否则不改变答案的值。

            3、以此类推,用Random函数抽取的范围不断加1,即Random rd = new Random(i),抽取范围为i,从0 -( i-1)中取道 i-1 的概率为1 / i。如果抽中i-1,把答案改为此时下标所指的数,否则不改变答案的值。

            4、直到链表为空,得到答案;

P(第 i 个数被选中) = (  1 / i  )* [1- 1/ ( i + 1 ) ] * [ 1-1 / ( i + 2 ) ] *... * [1-1 / ( n + 1 )]

                                   = (  1 / i  )* [ i / ( i + 1 ) ] * [ ( i + 1 ) / ( i + 2 ) ] *... * [ ( n  - 1 ) / ( n + 1 )] = 1 / n 

其中1- 1/ ( i + 1 )为第i+1个未选中的概率。

 

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */


public class LinkedListRandomNode382 {
	ListNode head;
	Random random;

	/**
	 * @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 LinkedListRandomNode382(ListNode head) {
		this.head = head;
		random = new Random();
	}

	/** Returns a random node's value. */
	public int getRandom() {
		ListNode c = head;
		int r = c.val;
		for (int i = 1; c.next != null; i++) {
			c = c.next;
			if (random.nextInt(i + 1) == i)
				r = c.val;
		}
		return r;
	}

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值