【发布时间】:2016-09-26 18:15:55
【问题描述】:
程序运行 100 次并打印出 140 个整数中的唯一元素。
由于需要比较两个整数来判断它们是否唯一,我如何打印出比较的总数?
这是我的代码:
public class UniqueElements {
public static void main(String[] args) {
// TODO code application logic here
Set<Integer> uniqueKeys = new TreeSet<Integer>();
//Use TreeSet to eliminate all duplicate integers in the array
for (int runs = 0; runs <= 100; runs++) { //program loops 100 times
for (int numbers = 1; numbers <= 140; numbers++) {
//add 140 integers in array
Random rand = new Random(System.nanoTime());
uniqueKeys.add(rand.nextInt(numbers));
//make the 140 integers random, including duplicates
}
System.out.print("Unique Elements: " + uniqueKeys + "\n");
//print unique elements in array
}
}
}
【问题讨论】:
-
您的代码并没有完全按照您的想法进行。它实际上从 140 个不同的范围(仅 0,然后是 0 或 1,然后是 0、1 或 2,等等)生成 14000 个整数。
-
是的,它在技术上是 14000 个整数,但它是 100 组数组,每个数组中有 140 个元素(减去重复项)。我运行它时很好。
-
System.out.println(14000);