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();
給定一單鏈表角寸,返回一隨機(jī)節(jié)點(diǎn)的值膀捷,每個(gè)節(jié)點(diǎn)被選中的概率必須一致墩弯。
進(jìn)階:
如果單鏈表非常大,且其長(zhǎng)度未知的情況將如何蒲每?能否在不使用額外空間的情況下解決這個(gè)問題瓣戚?
思路
【Reservoir Sampling 蓄水池抽樣問題】
(可理解為為等概抽樣問題)
問題:n個(gè)數(shù)中抽取k個(gè)沛慢,確保每個(gè)數(shù)被抽中的概率為n/k肾砂。
-
基本思路:
- 先選取1,2,3,...,k將之放入蓄水池;
- 對(duì)于k+1扣溺,將之以k/(k+1)的概率抽取骇窍,然后隨機(jī)替換水池中的一個(gè)數(shù)。
- 對(duì)于k+i锥余,將之以k/(k+i)的概率抽取腹纳,然后隨機(jī)替換水池中的一個(gè)數(shù)。
- 重復(fù)上述驱犹,直到k+i到達(dá)n嘲恍;
證明:
對(duì)于k+i,其選中并替換水池中已有元素的概率為k/(k+i)
對(duì)于水池中的某數(shù)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)
當(dāng)k+i到達(dá)n,則結(jié)果為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
對(duì)于本題医舆,取k=1即可
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
private:
ListNode* head;
public:
/** @param head The linked list's head. Note that the head is guanranteed to be not null, so it contains at least one node. */
Solution(ListNode* head) {
this->head = head;
}
/** Returns a random node's value. */
int getRandom() {
int res = head->val;
ListNode* node = head->next;
int i = 2;
while(node){
int j = rand()%i;
if(j==0)
res = node->val;
i++;
node = node->next;
}
return res;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/