整数数组中的重复数字(Java基本级别)&;时间复杂性
我创建了一个整数数组,并使用Math.random()用随机数初始化了这个数组 我试图在数组中打印重复的数字,而不使用Arraylist或Hashset。 我的代码(进行中): 它工作正常,但当数组中的一个数字重复两个以上时,它会打印多个数字。整数数组中的重复数字(Java基本级别)&;时间复杂性,java,arrays,algorithm,duplicates,Java,Arrays,Algorithm,Duplicates,我创建了一个整数数组,并使用Math.random()用随机数初始化了这个数组 我试图在数组中打印重复的数字,而不使用Arraylist或Hashset。 我的代码(进行中): 它工作正常,但当数组中的一个数字重复两个以上时,它会打印多个数字。 我怎样才能修好它?另一方面,我试图计算这个算法的时间复杂度,这是O(n)吗?不要使用布尔数组,而是使用另一个整数数组,因为你填充的元素最多可以是20,你可以创建一个大小为20的整数数组,每次你读取一个数字时都这样做,假设大小为20的数组称为“count”
我怎样才能修好它?另一方面,我试图计算这个算法的时间复杂度,这是O(n)吗?不要使用布尔数组,而是使用另一个整数数组,因为你填充的元素最多可以是20,你可以创建一个大小为20的整数数组,每次你读取一个数字时都这样做,假设大小为20的数组称为“count”
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);
}
int count[]=新的int[Length];
对于(int i=0;i<20;i++){
计数[a[i]]++;
}
对于(int i=0;i<20;i++){
如果(计数[i]>1)
系统输出打印LN(i);
}
这将打印出多次出现的数字。好吧,如果你执意不使用ArrayList(虽然这是最简单的),你可以创建一个布尔数组,长度是通过Math.random()函数选择的可能数字的范围(在本例中是0到19,表示范围是20)
private static boolean[]duplicatedNumbers=new boolean[20];
私有静态整数[]个数=新整数[20];
对于(int i=0;i
编辑:已修复并已测试。它应该是
count[a[i]]++
而不是count[i]++
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
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);
}
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 + ", ");
}
}