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

382. Linked List Random Node

2016-11-08 17:06 351 查看
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();


弱鸡解法:产生一个随机数,从头遍历到这个随机数代表的节点。
</pre><pre name="code" class="java">public class Solution {

/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
int len=0;
ListNode head;
Random rand;
public Solution(ListNode head) {
rand=new Random();
this.head=head;
ListNode n=head;
while(n!=null)
{
n=n.next;
len++;
}
}

/** Returns a random node's value. */
public int getRandom() {
ListNode node=head;
int step=rand.nextInt(len);
for(int i=0;i<step;i++)
node=node.next;
return node.val;
}
}

高级(精髓)解法:
理论------蓄水池抽样定理,参考 : Reservoir Sampling 蓄水池抽样算法,经典抽样
代码来自:https://discuss.leetcode.com/topic/53738/o-n-time-o-1-space-java-solution
public class Solution {

/** @param head The linked list's head. Note that the head is guanranteed to be not null, so it contains at least one node. */
ListNode head = null;
Random randomGenerator = null;
public Solution(ListNode head) {
this.head = head;
this.randomGenerator = new Random();

}

/** Returns a random node's value. */
public int getRandom() {
ListNode result = null;
ListNode current = head;

for(int n = 1; current!=null; n++) {
if (randomGenerator.nextInt(n) == 0) {
result = current;
}
current = current.next;
}

return result.val;

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