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

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