应用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;
};
本文介绍了一种称为Reservoir Sampling的算法,该算法能够在遍历整个数据集之前选取一个随机样本。文章通过数学推导解释了每个元素被选中的概率为1/n(n为数据集中元素的数量)。此外,还提供了一个C++实现示例,该示例展示了如何在一个链表中使用此算法随机选择一个节点。
868

被折叠的 条评论
为什么被折叠?



