2015-11-01 80 views
1

该方法返回一个array中元素之间的最大绝对差值。它会计算array中所有数字之间的差异,但我试图将其调整为返回最大绝对差值的索引数组中的元素

例如:

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; 
    } 
+0

这是一个assignement?我相信你能做到。只需一支钢笔和一张纸,一步一步地尝试。问问自己正确的问题。这是纯粹的逻辑,没有别的。 –

回答

0

您应该添加maxIndexmax,每次保存它,你更新max

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

您可避免储存max完全由maxIndex替换它,但你需要重新 - 在每次迭代时计算max,这可能是次优的。

+0

谢谢!这个if语句有效,但不适用于所有情况。例如,数组[4,18]需要返回1(因为是18 - 4),但它返回0. – Rods2292

+0

@ Rods2292这是因为你的循环错误地“环绕”了。你应该使条件或者'i <= array.length - 1'或'我 dasblinkenlight

+0

这是真的!我没有注意到'i <= array.length - 1'没有使用'='符号。 – Rods2292