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

382. Linked List Random Node

2016-08-20 15:51 417 查看
应用reservior sampling ,第i个被选中的概率为1/i,之后没有被选中的概率i-1/i,所以第1个被选中的概率为1/1*(1/2)*(2/3)*...(n-1)/n=1/n,

class Solution {
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) {
p=head;
}

/** Returns a random node's value. */
int getRandom() {
ListNode* h=p;
int val=h->val;
int len=0;
while(h)
{
if(rand()%(++len)==0)
val=h->val;
h=h->next;
}
return val;
}
private:
ListNode* p;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: