随机选择一组不同的整数的最有效的方法整数、最有效、不同、方法

2023-09-10 23:33:05 作者:每天过得都像复制粘贴

我在寻找最有效的算法随机选择一组n个不同的整数,其中所有的整数是在一定范围内[0..maxValue。

I'm looking for the most efficient algorithm to randomly choose a set of n distinct integers, where all the integers are in some range [0..maxValue].

约束:

包括maxValue是大于n,并且可能大得多 在我不在乎,如果输出列表进行排序或不 在所有整数必须以相同的概率选择

我最初的想法是构建整数[0..maxValue]然后提取n个元素的列表,随机无需更换。但是,这似乎很低效的,特别是如果包括maxValue是很大的。

My initial idea was to construct a list of the integers [0..maxValue] then extract n elements at random without replacement. But that seems quite inefficient, especially if maxValue is large.

没有更好的办法?

推荐答案

有关maxValue(最大值)的小值,这是合理的生成内存中的所有整数数组,那么你可以使用