题目地址: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;
/**
*原链接:http://bookshadow.com/weblog/2016/08/10/leetcode-linked-list-random-node/
* 数学归纳法:https://www.cnblogs.com/wanghai0666/p/5867174.html
* 蓄水池抽样(Reservoir Sampling)
* 蓄水池抽样算法的等概率性可以用数学归纳法证明:
* 一:当count等于1,抽出第1个的概率是1;
* 二:当count等于2,抽中第二个的概率是1/2;
* 三:假设抽取前k个元素的概率相等,均为1/k;
* 四:当抽取第k+1个元素时:
若0到k的可能性等于0,则返回值为第n+1个元素,其概率为1/(n+1);
否则,抽取的依然是前n个元素,其概率为1/n * n/(n+1) = 1/(n+1)
*/
public class LinkedListRandomNode {
private ListNode node;
Random random;
public LinkedListRandomNode(ListNode head) {
this.node = head;
random = new Random();
}
public int getRandom() {
int count = 1;
int res = node.val;
while (node.next != null) {
node = node.next;
if (random.nextInt(count + 1) == count) {
res = node.val;
}
count++;
}
return res;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
LinkedListRandomNode solution = new LinkedListRandomNode(head);
System.out.println(solution.getRandom());
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}