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

382. Linked List Random Node

2016-12-26 15:06 429 查看
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();

这题的关键在于理解蓄水池算法, http://blog.jobbole.com/42550/,http://blog.sina.com.cn/s/blog_48e3f9cd01019jyr.html。

public class Solution {
public ListNode head;
public Solution(ListNode head) {
this.head=head;
}
public int getRandom() {
int i=1,res;
ListNode l=head;
res=l.val;
while(l.next!=null){
l=l.next;
i++;
int m=(int)(1+Math.random()*i);
if(m==1)
res=l.val;
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: