leet382 https://leetcode.com/problems/linked-list-random-node/description/
leet398 https://leetcode.com/problems/random-pick-index/description/
基本原理:
k
从n
数字中选择条目。确保选择每个数字的概率为k/n
基本理念:
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 was in the reservoir last time)
×P(X is not replaced by k+i)
- =
P(X was in the reservoir last time)
×(1
-P(k+i is selected and replaces X)
) - =
k/(k+i-1)
×(1
-k/(k+i)
×1/k
) - =
k/(k+i)
- 当
k+i
达到n
,每个号码的留在储存器中的概率是k/n
例
3
从中选择数字[111, 222, 333, 444]
。确保选择每个数字的概率为3/4
- 首先,选择
[111, 222, 333]
作为初始储备 - 选择然后
444
概率为3/4
- 因为
111
,它的概率为P(444 is not selected)
+P(444 is selected but it replaces 222 or 333)
- =
1/4
+3/4
*2/3
- =
3/4
- 与
222
状语从句:相同的情况333
- 所有现在都有数字可能
3/4
被选中