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

382.[LeetCode]Linked List Random Node(蓄水池算法)

2016-08-27 16:12 537 查看
参考资料:非常的好的文章,一看就会

此题要使用的是 经典的蓄水池算法,该方法的使用场景是 数据流长度未知,要求随机

public class Solution {

private ListNode head;

/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. 至少有一个node,默认链表不为空*/
public Solution(ListNode head) {
this.head = head;
}

/** Returns a random node's value. */
// 这个方法的时间复杂度为 O(n)
public int getRandom() {
int count = 1;
ListNode currentNode = head;
int val = currentNode.val;
Random r = new Random();
while(currentNode != null){ // 这里是一个bug点,经常写成currentNode.next导致最后一个element没有进入操作
// nextInt 方法生成一个 介于[0,n)的数,包含0,但是不包含n
if(r.nextInt(count++) == 0){
val = currentNode.val;
}
currentNode = currentNode.next;
}
return val;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode