蓄水池算法:解决随机采样问题,每个元素被采样的概率相等
leetcode题目:https://leetcode-cn.com/problems/linked-list-random-node/submissions/
代码:
class Solution {
// 蓄水池算法,随机从n个元素里取k个
// 1.前k个元素入数组int[k]
// 2.后面第i个(i >= k), k/(i + 1)概率替换 int[k]中一个-----------i从0开始
// 3.遍历一次后,int[k]即为随机采样出来的
private Random random;
private ListNode head;
/** @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;
this.random = new Random();
}
/** Returns a random node's value. */
public int getRandom() {
int ans = head.val;
ListNode cur = head.next;
int k = 2;
while (cur != null) {
if (random.nextInt(k++) == 0) {
ans = cur.val;
}
cur = cur.next;
}
return ans;
}
}
参考
证明过程请看下面连接
————————————————
版权声明:本文为CSDN博主「wwxy261」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/wwxy1995/article/details/102974566