在一个范围内生成不同的随机数[重复]

时间:2022-08-24 04:19:33

This question already has an answer here:

这个问题已经有了答案:

I want to generate n different numbers between 1 and N (of course n<=N). N could be very large. If n is very small, one efficient way is generating a numbers and compare it with the set we have got to make sure it's a new number. It takes O(n^2) time and O(n) memory. If n is quite large, we can use Fisher–Yates shuffle algorithm to generate a random permutation( stop after n steps). It takes O(n) time, but we also must use O(N) memory.

我想在1和n之间生成n个不同的数(当然是n<= n)N可以很大。如果n很小,一种有效的方法是生成一个数字并与我们要确定它是一个新数字的集合进行比较。需要O(n ^ 2)时间和O(n)的记忆。如果n相当大,我们可以使用Fisher-Yates洗牌算法生成一个随机排列(n步后停止)。它需要O(n)时间,但我们也必须使用O(n)内存。

Here is the question. What can we do if we do not know how large n is? I hope that the algorithm just use O(n) memory and stop after O(n) time. Is that possible?

这是问题。如果我们不知道n有多大,我们能做什么?我希望该算法只使用O(n)内存并在O(n)时间后停止。这有可能吗?

1 个解决方案

#1


0  

You can essentially do the same as for very small n, but just make that check more efficient. For example the naïve method of checking if you've already generated a number is to just linearly search the list of previously generated values. For an unknown n you could keep the set of previously generated values sorted so that you can use a more efficient search for identifying duplicates. With the naïve approach the algorithm takes O(n2) time, but a smarter search through previous results can reduce that to O(n*log2 n).

你可以对非常小的n做相同的操作,但是只需要让它更有效。例如,检查是否已经生成一个数字的幼稚方法是线性搜索先前生成的值的列表。对于未知的n,可以对之前生成的值进行排序,以便使用更有效的搜索来识别重复的值。用简单的方法,算法采用O(n2)时间,但通过之前的结果进行更智能的搜索可以将其减少到O(n* log2n)。

#1


0  

You can essentially do the same as for very small n, but just make that check more efficient. For example the naïve method of checking if you've already generated a number is to just linearly search the list of previously generated values. For an unknown n you could keep the set of previously generated values sorted so that you can use a more efficient search for identifying duplicates. With the naïve approach the algorithm takes O(n2) time, but a smarter search through previous results can reduce that to O(n*log2 n).

你可以对非常小的n做相同的操作,但是只需要让它更有效。例如,检查是否已经生成一个数字的幼稚方法是线性搜索先前生成的值的列表。对于未知的n,可以对之前生成的值进行排序,以便使用更有效的搜索来识别重复的值。用简单的方法,算法采用O(n2)时间,但通过之前的结果进行更智能的搜索可以将其减少到O(n* log2n)。