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 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解