可能重复: How你高效地生成介于0和上限ñ k条非重复的整数列表
什么是一些其他方法来生成1000不同的随机整数的范围为[0,8000],而不是为以下内容:
天真的方法:产生一个数字,并检查它是否已经到数组中。为O(n ^ 2) 线性洗牌:生成序列0到8000,洗牌,取前1000 O(N) 解决方案您可以使用部分的费雪耶茨洗牌实现使用互换。一个该算法的不错的功能是,如果你在 K
互换停止,第一个 K
数字是随机的大小样品 K
从配套。
Possible Duplicate: How do you efficiently generate a list of K non-repeating integers between 0 and an upper bound N
What are some alternative methods to generate 1000 distinct random integers in the range [0,8000] as opposed to the following:
naive method: generating a number and checking if it's already in the array. O(n^2) linear shuffle: generate sequence 0 to 8000, shuffle, take the first 1000. O(n)解决方案
You can use a partial Fisher-Yates shuffle implemented using swaps. One of the nice features of this algorithm is that if you stop after k
swaps, the first k
numbers are a random sample of size k
from the complete set.