【发布时间】:2015-08-20 11:56:56
【问题描述】:
我希望生成 500000 个 1 到 100 万范围内的唯一随机整数。这些数字必须是唯一的,我希望它在 至少 线性时间内并且不使用太多内存。有人能想到解决办法吗?
【问题讨论】:
标签: java algorithm time-complexity space-complexity
我希望生成 500000 个 1 到 100 万范围内的唯一随机整数。这些数字必须是唯一的,我希望它在 至少 线性时间内并且不使用太多内存。有人能想到解决办法吗?
【问题讨论】:
标签: java algorithm time-complexity space-complexity
与之前的was said 一样,您可以将数字随机排列,然后拉出前半部分,这样它们将是唯一的。这是线性的,因为洗牌是O(n),而第一部分是O(n/2)。
Hare 是该线程的修改实现。这将打印 1-1m 范围内的 500k 个唯一随机数。
import java.util.ArrayList;
import java.util.Collections;
public class UniqueRandomNumbers {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=1; i<1000001; i++) {
list.add(new Integer(i)); // adding all the numbers between 1-1m to a list.
}
Collections.shuffle(list); // using the built in shuffle function to make the unique order
for (int i=0; i<500000; i++) {
System.out.println(list.get(i)); // printing the first 500k. Replace this with whatever you want to do with those numbers.
//Notice - since it might take a while, it might be worth it to let the user know of the progress.
}
}
}
【讨论】:
如果内存非常宝贵,请使用位图来记住选择了百万中的哪一个,然后反复选择一个随机数并在 500,000 后停止。这基本上是存储最优的,因为 lg(1e6 choose 0.5e6) 并不比 1e6 小很多。
【讨论】: