[LeetCode]382. Linked List Random Node

来源:互联网 发布:网络教育的发展前景 编辑:程序博客网 时间:2024/04/29 11:52

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的valuepublic 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;}}


0 0
原创粉丝点击