如何返回数组中匹配数字之间的最小距离?



我试图找到未排序数组中两个匹配数字之间的最小距离。如果无法找到匹配项,则返回 -1。 我正在使用的数组 int[] 数组 = {5, 3, 4, 2, 3, 4, 5, 7};

我已经尝试了两个 for 循环和两个辅助方法,将数组中的第一个元素与其他元素进行比较,并将计数器变量增加一个,直到我达到匹配。然后我将计数器与最小值进行比较,我将其设置为可能的最大整数。我不确定为什么它不起作用。对于此示例,它应该返回 4。

int[] array = {5, 3, 4, 2, 3, 4, 5, 7};
int counter = 0;
int min = Integer.MAX_VALUE;
if(hasDuplicates(array)) {
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if(array[i] != array[j]){
counter++;
}
}
min = min(counter, min);
counter = 0;
}
System.out.println(min);
} else {
System.out.println("-1");
}
}
public static boolean hasDuplicates(int[] array) {
boolean isDuplicates = false;
Set<Integer> duplicates = new HashSet<Integer>();
for (int element : array){
if(duplicates.contains(element)) {
isDuplicates = true;
}
duplicates.add(element);
}
return isDuplicates;
}
public static int min(int a, int b){
if (a >b){
return a;
} else {
return b;
}
}

我希望此方法的输出为 4,但此代码的实际输出2147483647。

好的,我刚刚弄清楚问题出在哪里。

在原始代码中,如果两个数字不匹配,您不应该尝试使用计数器来帮助找出距离。相反,如果两者相互匹配,您可以尝试直接计算距离。

代码如下所示:

public void find() {
int[] array = {5, 3, 4, 2, 3, 4, 5, 7};
//int counter = 0;
int min = Integer.MAX_VALUE;
if(hasDuplicates(array)) {
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
/*if(array[i] != array[j]){
counter++;
}*/
if(array[i] == array[j]){
min = Math.min(min, j - i);
}
}
//min = min(counter, min);
/*if (counter > 0)
min = Math.min(counter, min);
counter = 0;*/
}
System.out.println(min);
} else {
System.out.println("-1");
}
}

然后你会得到3

2147483647是整数最大值。您的 min 函数实际上返回两个参数的 max。将比较更改为小于。

public static int min(int a, int b){ if (a <b){ return a; } else { return b; }

或者使用Math.min。

最新更新