https://leetcode.com/problems/linked-list-random-node/
随机获取链表中某个节点的值
蓄水池算法,遍历链表。在位置i处时,随机[0, i)如果得到i - 1,则res赋值位置i处的node值;反之res不变,指针后移。最终每个节点取到的概率相同。位置k处渠道的概率为:
(1 / k) * (k / k + 1) * …… * (n - 1 / n) = 1 / n
public class Solution {
ListNode head;
Random random;
public Solution(ListNode head) {
this.head = head;
this.random = new Random();
}
// 返回随机取出的node的value
public int getRandom() {
int res = head.val;
int count = 1;
ListNode cur = head;
while (cur != null) {
if (random.nextInt(count) == count - 1) {
res = cur.val;
}
count++;
cur = cur.next;
}
return res;
}
}