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:
这题的关键在于理解蓄水池算法, 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;
}
}
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;
}
}
相关文章推荐
- leetcode 382 Linked List Random Node C++
- 边刷leetcode边学编程-382 Linked List Random Node
- 382. Linked List Random Node
- 382. Linked List Random Node
- 382. Linked List Random Node
- LeetCode 382 Linked List Random Node (蓄水池算法 推荐)
- 382. Linked List Random Node
- leetcode: Reservoir Sampling:Linked List Random Node(382)
- 382. Linked List Random Node
- 382. Linked List Random Node (M)
- 382. Linked List Random Node
- 382. Linked List Random Node
- 382 linked list random node (待解决)
- 382. Linked List Random Node
- [leetcode] 382. Linked List Random Node
- 382. Linked List Random Node
- leetcode382 Linked List Random Node java
- [leetcode][382] Linked List Random Node
- 382. Linked List Random Node
- LeetCode:382 Linked List Random Node