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

Linked List Random Node

2016-10-24 10:20 197 查看

Linked List Random Node

Total Accepted: 13046
Total Submissions: 28645
Difficulty: Medium
Contributors: Admin

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()
 


代码:

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
ListNode *h;

public:
/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
Solution(ListNode* head) {
h=head;
}

/** Returns a random node's value. */
int getRandom() {
int ans=h->val;
ListNode *node=h;
int chunum=1;
while(node)
{
if(rand()%chunum==0)
ans=node->val;
chunum++;
node=node->next;
}
return ans;
}
};

/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/

分析:从前遍历每个节点,并判断该节点是不是要留下来的节点,若一共有N个节点,则每个节点的概率为
1.   1*1/2*2/3*...(n-1)/n=1/n;     第一个节点被选中,后面的节点都未被选中


2.   1/2*[b]2/3*...(n-1)/n=1/n;  弟二个节点被选中,[b]后面的节点都未被选中
[/b][/b]

3.   1/3*3/4*[b][b]...(n-1)/n=1/n;    第三个[b][b]节点被选中,[b]后面的节点都未被选中[/b][/b][/b][/b]
[/b]

....

所以每个节点被选中的概率都为1/n;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode random