您的位置:首页 > Web前端 > Node.js

LeetCode 382 Linked List Random Node

2017-07-01 11:52 417 查看
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();


大意是说给你一个链表,长度未知,等概率随机选出一个。这就需要蓄水池算法。

蓄水池算法用于解决在N个元素中等概率随机选出k个(0<k<N).N可以未知或者很大。

具体做法如下:

1 给N个元素标号为1-N

2 遍历,将前k个元素加入候选集合

3 当标号大于k时,假设为i,如果元素只有i个,那么每个元素被选中的概率应该是k/i,为此做如下操作:

对第i个元素,以k/i的概率将i号元素加入候选集合,以1/k的概率从候选集合中移除一个原来元素。如果每个元素留在集合的概率是i/k那么算法就正确。

证明(数学归纳法):

3.1 当i=k+1时,第i个元素加入候选集合的概率是1/i,前i个元素被留下概率是1-(k/(k+1))*(1/k)=k/(k+1)

3.2 当i>k时,假设前i个元素每一个被加入候选集合的概率是k/i

3.3 当i=i+1时,前i个元素每一个被加入候选集合的概率是(k/i)*(1-(k/(i+1))*(1/k)),化简可得k/(i+1),第i+1个显然也是k/(i+1)

3.4 得证

具体到这个题只要把k换成1就行了。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

public static void main(String[] args) {
// TODO Auto-generated method stub
Random ran = new Random();
System.out.println(ran.nextInt(1));
}
public class ListNode {
int val;
ListNode next;
 
ListNode(int x) {
val = x;
}
}
 
ListNode head;
Random ran;
 
public Solution_382(ListNode head) {
this.head = head;
ran = new Random();
}
 
/** Returns a random node's value. */
public int getRandom() {
ListNode node = head;
int current = 0;
for (int i = 1; node != null; i++) {
current = ran.nextInt(i) == 0 ? node.val : current;
node=node.next;
}
return current;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 leetcode random