给定一个单链表,随机选择链表的一个节点,并返回相应的节点值。保证每个节点被选的概率一样。
进阶:
如果链表十分大且长度未知,如何解决这个问题?你能否使用常数级空间复杂度实现?
示例:
// 初始化一个单链表 [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()方法应随机返回1,2,3中的一个,保证每个元素被返回的概率相等。
solution.getRandom();
思路
【Reservoir Sampling 蓄水池抽样问题】
(可理解为为等概抽样问题)
-
问题:n个数中抽取k个,确保每个数被抽中的概率为n/k。
-
基本思路:
- 先选取1,2,3,...,k将之放入蓄水池;
- 对于k+1,将之以k/(k+1)的概率抽取,然后随机替换水池中的一个数。
- 对于k+i,将之以k/(k+i)的概率抽取,然后随机替换水池中的一个数。
- 重复上述,直到k+i到达n;
-
证明:
对于k+i,其选中并替换水池中已有元素的概率为k/(k+i)
对于水池中的某数x,其之前就在水池,一次替换后仍在水池中的概率是
P(x之前在水池) * P(未被k+i替换)
=P(x之前在水池) * (1-P(k+i被选中且替换了x) )
= k/(k+i-1) × (1 - k/(k+i) × 1/k)
= k/(k+i)
当k+i到达n,则结果为k/n -
举例
- Choose 3 numbers from [111, 222, 333, 444]. Make sure each number is selected with a probability of 3/4
- First, choose [111, 222, 333] as the initial reservior
- Then choose 444 with a probability of 3/4
- For 111, it stays with a probability of
- P(444 is not selected) + P(444 is selected but it replaces 222 or 333)= 1/4 + 3/4*2/3= 3/4
- The same case with 222 and 333
- Now all the numbers have the probability of 3/4 to be picked
对于本题,取k=1即可
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
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. */
ListNode* node;
Solution(ListNode* head) {
this->node=head;
}
/** Returns a random node's value. */
int getRandom() {
int res=node->val;
int i=2;
ListNode *p=node->next;
while(p!=nullptr)
{
if(rand()%i==0)
res=p->val;
i++;
p=p->next;
}
return res;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(head);
* int param_1 = obj->getRandom();
*/