Problem #15 [Medium]

本文介绍了解决内存受限情况下,如何使用循环不变量实现从大数据流中均匀随机选择元素的算法,空间复杂度降低到O(1),并通过Python代码展示了这一优化过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

This problem was asked by Facebook.

Given a stream of elements too large to store in memory, pick a random element from the stream with uniform probability.
这是个经典面试问题:蓄水池抽样。如果没有内存限制,我们可以把stream存到一个列表中,然后从[0, size-1]中随机选择元素,空间复杂度为O(N)。

import random
random_element = random.choice(my_list)

print(random_element)

相反,让我们尝试使用循环不变量来解决。在循环的第 i 次迭代中选择随机元素时,假设我们已经从 [0, i - 1] 中统一选择了一个元素。为了保持循环不变,我们需要以 1 / (i + 1) 的机会选择第 i 个元素作为新的随机元素。对于 i = 0 的基本情况,假设随机元素是第一个。然后我们知道它有效,因为

对于 i = 0, we would’ve picked uniformly from [0, 0].
对于 i > 0, before the loop began, any element K in [0, i - 1] had 1 / i chance of being chosen as the random element. We want K to have 1 / (i + 1) chance of being chosen after the iteration. This is the case since the chance of having being chosen already but not getting swapped with the ith element is 1 / i * (1 - (1 / (i + 1))) which is 1 / i * i / (i + 1) or 1 / (i + 1)
代码如下:

import random

def pick(big_stream):
    random_element = None

    for i, e in enumerate(big_stream):
        if i == 0:
            random_element = e
        if random.randint(1, i + 1) == 1:
            random_element = e
    return random_element

空间复杂度为O(1)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值