我创建了一个整数数组,并使用Math.random()将该数组初始化为随机数。
我试图在不使用Arraylist或Hashset的情况下在数组中打印重复的数字。 我的代码(正在进行中):
public class Test{
public static final int Length = 20;
public static void main(String[] args) {
int a[]= new int[Length];
for(int i=0; i<a.length; i++){
a[i]=(int)(Math.random()*Length);
}
for(int i=0; i<a.length; i++){
System.out.print(a[i]+" ");
}
System.out.println();
isDuplicate(a);
System.exit(0);
}//eof main
public static void isDuplicate(int a[]){
System.out.print("Duplicates: ");
boolean test[] = new boolean[Length];
for(int i=0; i<test.length; i++){
test[i]=false;
}
for(int i=0; i<a.length; i++){
if(test[a[i]]==false){
test[a[i]]=true;
}
else
System.out.print(a[i]+" ");
}
System.out.println();
}//eof isDuplicate
}
示例输出:
16 15 12 7 0 7 2 14 12 18 1 8 2 15 4 5 6 5 12 7
Duplicates: 7 12 2 15 5 12 7
The correct output has to be : 7 12 2 15 5
它工作正常但是当数组中的数字重复超过两个时,它会打印多个数字。 我该如何解决?另一方面,我试图计算这个算法的时间复杂度,这是O(n)?
答案 0 :(得分:1)
使用另一个整数数组,而不是使用布尔数组,因为你正在填充最多20个元素,你可以创建一个大小为20的整数数组,每次读取数字都会这样做,假设数组大小为20的被称为&#39; count&#39;。
int count[] = new int[Length];
for(int i = 0; i < 20; i++) {
count[a[i]]++;
}
for(int i = 0; i < 20; i++) {
if(count[i] > 1)
System.out.println(i);
}
这将打印出多次出现的数字。
答案 1 :(得分:0)
好吧,如果你没有使用ArrayList(尽管这是最容易的),你可以创建一个布尔数组,其长度是通过Math.random()函数选择的可能数字的范围(在这种情况下为0到19,表示范围是20)。
private static boolean[] duplicatedNumbers = new boolean[20];
private static int[] numbers = new int[20];
for(int i = 0; i < duplicatedNumbers.length; i++){
duplicatedNumbers[i] = false;
}
for(int i = 0; i < numbers.length; i++){
numbers[i] = (int) (Math.random() * 20);
}
for(int i = 0; i < numbers.length; i++){//this for loop finds out which ones are duplicated
for(int j = 0; j < numbers.length; j++){
if(j!=i && numbers[j] == numbers[i]){
duplicatedNumbers[numbers[j]] = true;
}
}
}
System.out.print("Numbers: ");
for(int i = 0; i < numbers.length; i++){
System.out.print(numbers[i] + ", ");
}
System.out.println();
System.out.print("Duplicated Numbers: ");
for(int i = 0; i < duplicatedNumbers.length; i++){
if(duplicatedNumbers[i]){
System.out.print(i + ", ");
}
}
编辑:已修复并经过测试。