gpt4 book ai didi

java - 数组中的元素

转载 作者:太空宇宙 更新时间:2023-11-04 13:16:54 25 4
gpt4 key购买 nike

此方法返回一个数组中元素之间的最大绝对差。它计算数组中所有数字之间的差异,但我正在尝试调整它以返回最大绝对差异的索引

例如:

Array = [7, 19, 5, 10, 16, 8, 1, 19, 6, 13] 
Index = [0, 01, 2, 03, 04, 5, 6, 07, 8, 09]

在此数组中,最大的绝对差异是 18 (= 1-19),它发生在索引号 6 中。

此外,如果存在多个相等的差异,该方法需要返回索引较高的一个。在上面的示例中,它将返回索引 3 而不是 0

    Array = [1, 19, 5, 1, 19]
Index = [0, 01, 2, 3, 04]

这个问题有点复杂,我不知道该怎么做。有谁知道吗?

public static int stepMaxDiff(int[] array){

int diff = 0;
int max = 0;

if (array.length == 0){ // Checks for empty array and returns -1
return -1;
}

for (int i = 0; i < array.length - 1; ++i){ // i is the element in the array

if (i == array.length - 1){
diff = Math.abs(array[i] - array[0]);
// Calculates the last element of the array minus the first one

} else {
diff = Math.abs(array[i] - array[i+1]);
// Calculates the element i minus element [i+1]
}

max = diff >= max ? diff : max;
}

return max;
}

最佳答案

您应该将 maxIndex 添加到 max,并在每次更新 max 时存储它:

if (diff >= max) {
max = diff;
maxIndex = i;
}

您可以避免完全存储 max,而是将其替换为 maxIndex,但随后您需要在每次迭代时重新计算 max,这可能不是最优的。

关于java - 数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33468435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com