*Linked List Random Node

Posted Hygeia

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了*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;
public class Solution {
    private ListNode head;
    private int size;
    Random randGen = new Random();
    /** @param head The linked list‘s head. Note that the head is guanranteed to be not null, so it contains at least one node. */
    public Solution(ListNode head) {
        this.head = head;
        ListNode current = head;
        while (current != null) { size++; current = current.next; }
        this.size = size;
    }
    
    /** Returns a random node‘s value. */
    public int getRandom() {
        int pos = randGen.nextInt(size);
        ListNode current = head;
        for (int i =0; i < pos; i++) current = current.next;
        return current.val;
    }
}



解法二:蓄水池抽样

在遍历到第i个数时设置选取这个数的概率为1/i, 然后来证明一下每个数被选到的概率:
对于第一个数其被选择的概率为1/1*(1-1/2)*(1-1/3)*(1-1/4)*...*(1-1/n) = 1/n, 其中(1-1/n)的意思是不选择n的概率,
也就是选择1的概率乘以不选择其他数的概率. 对于任意一个数i来说, 其被选择的概率为1/i*(1-1/(i+1))*...*(1-1/n),
所以在每一个数的时候我们只要按照随机一个是否是i的倍数即可决定是否取当前数即可.
详细证明和讲解:
http://blog.csdn.net/yeqiuzs/article/details/52169369

所以当遍历到第cnt个数的时候,保证选取这个数的概率为1/cnt,即可最后保证所有数被抽取的概率相等,皆为1/n
import java.util.Random;
public class Solution {
    private ListNode head;
    private Random random;
    /** @param head The linked list‘s head. Note that the head is guanranteed 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 = 0;
        ListNode p = head;
        for (int cnt = 1; p != null; cnt++, p = p.next) if (random.nextInt(cnt) == 0) ans = p.val;//nextInt(cnt)产生0-cnt随机数,其中等于0的概率正好为1/cnt
        return ans;
    }
}

reference:

https://www.hrwhisper.me/leetcode-linked-list-random-node/

http://blog.csdn.net/yeqiuzs/article/details/52169369

以上是关于*Linked List Random Node的主要内容,如果未能解决你的问题,请参考以下文章

382. Linked List Random Node

Leetcode: Linked List Random Node

382. Linked List Random Node

382. Linked List Random Node 链接列表随机节点

Reservoir Sampling-382. Linked List Random Node

LeetCode: Linked List Random Node