学习一下蓄水池抽样 看完似懂非懂 嗷呜
即:当内存无法加载全部数据时,如何从包含未知大小的数据流中随机选取k个数据,并且要保证每个数据被抽取到的概率相等。
java:
class Solution {
ListNode head;
Random random;
public Solution(ListNode head) {
this.head = head;
random = new Random();
}
public int getRandom() {
int i = 1, ans = 0;
for (ListNode node = head; node != null; node = node.next) {
if (random.nextInt(i) == 0) {
ans = node.val;
}
++i;
}
return ans;
}
}
python3:
class Solution:
def __init__(self, head: Optional[ListNode]):
self.head = head
def getRandom(self) -> int:
node, i, ans = self.head, 1, 0
while node:
if randrange(i) == 0:
ans = node.val
i += 1
node = node.next
return ans