给定一个单链表,随机选择链表的一个节点,并返回相应的节点值。保证每个节点被选的概率一样。
进阶:
如果链表十分大且长度未知,如何解决这个问题?你能否使用常数级空间复杂度实现?
示例:
// 初始化一个单链表 [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,但是我们事先不知道n,求从中取k个数且保证每个数的取得概率相同,均为k/n。
方法:初始化数组长度为k,对于前k个数,放入数组不做处理。
对于第k+1个数,需要与数组中某个数(假设为x)交换的概率为k/(k+1),那么可以证明对每个数直到处理到n个数,每个数仍然在数组中的概率相同,均为k/n。
假设以第i个数为例,第i个数第i次放入数组的概率为k/i,对于数i+1,第i个数不被换出的情况等于=(1-第i个数被换出来的概率)=(1-(第i+1个数的取得概率随机替换)*第i个数被选择的概率)=(1-k/(i+1)*(1/k))=1-1/(i+1),同理第i+2个数进来也是这么分析,直到第n个数,所以第i个数最后依然在数组中的概率为:
具体分析:对于这道题,我们取k=1,n为不知道的大数。那么我们的思路如下:
Init : a reservoir with the size: k
for i= k+1 to N //k=1
M=random(1, i);
if( M < k)
SWAP the Mth value and ith value
end for
参考代码:
/**
* 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. */
Solution(ListNode* head) {
this->head = head;
}
/** Returns a random node's value. */
int getRandom() {
int res = head->val;
ListNode* next = head->next;
int i = 2;
while (next) {
int div = rand() % i;
if (div == 0) res = next->val;
i++;
next = next->next;
}
return res;
}
private:
ListNode* head;
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/