Leetcode 蓄水池抽样:随机取值

it2023-12-31  60

返回链表中任意一个节点的值,确保每个节点被选中的概率相等:

遇到第K个节点时,以1/k的概率选中为返回值,意味着:

前面选中的节点可能被当前K节点替换掉当前若选中K节点,也可能被之后的节点替换掉 node* random(node* head) { int count=0; node* ret=NULL; while(head) { count++; if((rand()%count)==0) ret=head; head=head->next; } return ret; }

进一步,若需要返回其中任意K个点,(保证长度大于K) 思路:

初始化选取K个节点

往后的每一个节点i :

产生一个0到i的随机数  rand()%count 若这个数落在0-k之间,那么替换对应位置的数。 vector<node*> randomK(node* head,int k) { vector<node*> res; int count=0; while(head && count<k) { count++; res.push_back(head); head=head->next; } while(head) { count++; if(rand()%count<k) { res[rand()%count]=head; } head=head->next; } return res; }

证明:

①对于前面的K个数字,其开始被选中的概率为:1

从第K+1个数字开始,其被替换出的概率为:

因此其最终没有被替换出的概率(选中)为: 

 

②而对于从K+1开始的数字i,其被选中进入的概率为:

其在之后不被替换出的概率为:

因此其最终没有被替换出的概率(选中)为:

 

 

 

 

最新回复(0)