[英]Create a function that checks to see if any indexes in the array are of the same value
我正在尝试创建一个函数来检查数组中是否有两个索引具有相同的值。 我已经意识到下面的代码仅检查第一个索引是否与第二个索引相同,而不检查第一个索引是否与第三个,第四个索引相同,依此类推。
我尝试在for循环中使用for循环比较每个索引,但是我不知道如何使它工作。
由于我当前的实现,由于i + 1超出了数组的长度,因此我也获得了索引超出范围的异常。
如果有人可以帮助解决代码并向我解释它如何工作,那就太好了! 谢谢!
public class Values {
public static void main (String[]args){
int[] A = {0,1,2,1,4};
for(int i = 0;i<=A.length;i++){
int n = i+1;
if(A[i] == A[n]){
System.out.println("Index " + i + " is the same value as index " + n);
System.out.println("Therefore, not all of the values in the array are different");
break;
}
}
System.out.println("All indexes in the array contain different values");
}
}
for(int i = 0; i < A.length - 1; i++){
for(int j = i + 1; j < A.length; j++){
if(A[i] == A[j]){
//do something
}
}
}
最有效的方法是先排序,然后查找两个相邻元素是否相等:
Arrays.sort(A);
for (int i = 0; i < A.length - 1; i++)
if (A[i] == A[i+1])
// do something
由于排序,该算法的时间复杂度为O(n log n)。
使用嵌套循环的时间复杂度为O(n 2 ),即使数组大小适中,也会开始受到损害。 再加上代码更简单。
出现边界异常的原因是因为数组的长度为5(1、2、3、4、5个元素),但是只能访问索引A [0],...,A [4]-因此,您应该像这样遍历数组: for(int i = 0;i<A.length;i++)
public class Values {
public static void main (String[]args){
int[] a = {0,1,2,1,4};
boolean foundMatch = false;
for(int i = 0;i < a.length; i++){
if (foundMatch)
break;
for (int j = i+1; j < a.length; j++) {
if (a[i] == a[j]){
System.out.println("Index " + i + " & " + j + " contain the same element: " + a[i] + "\nEnding comparison.");
foundMatch = true;
break;
}
}
}
if(!foundMatch)
System.out.println("All indexes in the array contain different values");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.