[LeetCode]382. Linked List Random Node
2016-09-10 12:24
246 查看
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?解答:我们没法提前知道长度,这里用到了著名了水塘抽样的思路,由于限定了head一定存在,所以我们先让返回值res等于head的节点值,然后让cur指向head的下一个节点,定义一个变量i,初始化为2,若cur不为空我们开始循环,我们在[0,i - 1]中取一个随机数,如果取出来0,那么我们更新res为当前的cur的节点值,然后此时i自增一,cur指向其下一个位置,这里其实相当于我们维护了一个大小为1的水塘,然后我们随机数生成为0的话,我们交换水塘中的值和当前遍历到底值,这样可以保证每个数字的概率相等,参见代码如下:
class Solution {public:Solution(ListNode* head) {this head;}int getRandom() {int res=head->val,j=2;ListNode *cur=head->next;while(cur){int k=rand()%j;if(k==0)res=cur->val;cur=cur->next;j++;}return res;}private:ListNode *head;};
相关文章推荐
- leetcode--Minimum Depth of Binary Tree
- [LeetCode]Longest Consecutive Sequence, 解题报告
- [leetcode]_Palindrome Number
- [LeetCode] Minimum Path Sum
- Leetcode--Permutations II
- LeetCode: Binary Tree Level Order Traversal 解题报告
- Convert Sorted Array to Binary Search Tree - Leetcode
- https://leetcode.com/problems/climbing-stairs/
- 【LeetCode】23.Merge k Sorted Lists
- LeetCode(54)(59) Spiral Matrix I II
- LeetCode Copy List with Random Pointer
- LeetCode---Kth Smallest Element in a BST
- Leetcode: H-Index II
- 【leetcode】Array—— Pascal's Triangle and Pascal's Triangle II(118/119)
- [LeetCode]Longest Increasing Subsequence
- Leetcode 之Evaluate Reverse Polish Notation(41)
- [LeetCode] 45. Jump Game II
- 【Leetcode 166】 Fraction to Recurring Decimal
- [LeetCode109]Convert Sorted List to Binary Search Tree
- 【LeetCode】 122. Best Time to Buy and Sell Stock II