在链表中查找元素

时间:2015-05-25 18:21:59

标签: algorithm linked-list computer-science

有一个数据结构为迭代器提供以下接口:

struct iterator {
    T value();
    void next();
    bool isValid();
}

如何设计一个算法,该算法在循环结束时从列表中返回一些值,每个元素的概率相等?列表可能很长,因此列表的长度不能用int或long表示。该列表无法修改。

有什么想法吗? 感谢。

1 个答案:

答案 0 :(得分:3)

您不知道列表的长度,因此您必须一直迭代到最后。您需要保留当前所选项目值(或项目)的副本,但在您的问题中似乎无法做到这一点。然后,对于您迭代的每个新项目,您需要确定是否应保留或更改所选项目,并降低概率。

因为您声明列表的长度可能不适合本机/原始数据类型(我假设您的意思是当您谈论intlong时,这些是编程语言甚至是方言特定的数据类型,你没有指定编程语言),我认为你的意思是列表可能是任意长的。所以你需要一个bignum库,可以给你任意随机数。

伪代码:

T current = empty value
bignum index = 0
iterator = first item of list
while iterator.isValid()
    index = index + 1
    if bignum_random_below(index) == 0
        # 0 is interpreted as, take value from current index,
        # everything else is interpreted as keep the previous value
        current  = iterator.value()
    end if
    iterator.next()
end while
# index value 0 indicates empty list, even if T doesn't have empty value

来自M Oehm的评论:这被称为reservoir sampling