数组中相邻元素之间的最小间隙

时间:2014-06-01 21:20:00

标签: java arrays

我正在研究一种方法,该方法在一个充满整数的数组中打印两个相邻值之间的最小间隙。我的代码编译,但我认为我的公式可能是错的。最终结果应该只是一个最小值。有什么建议吗?

public static void minGap(int[] list) { //pass it an array of random integers
    int min = 0;
    int gap = 0;
    for (int i = 0; i < list.length; i++) { //cycle through the array
        for (int j = 0; j < list.length; j++) {
            gap = ((i + 1) - i);
        }
        System.out.println("The minimum gap between 2 adjacent values is " + gap + " ");
    }
}

2 个答案:

答案 0 :(得分:1)

public static void minGap(int[] list) { //pass it an array of random integers
   // initialize gap with difference of first two elements of array             
   int gap = Math.abs(list[1] - list[0]);
   // Start the array iteration from second element as we already have difference of first two elements.
   for(int i = 2; i < list.length; i++) { //cycle through the array
      // calculate the difference between two adjacent element. 
      int absDiff = Math.abs(list[i] - list[i-1]); 
      // if the difference is less then the prior minimum it becomes the new minimum.
      if(gap > absDiff) {           
         gap = absDiff;
      }
   }
   System.out.println("The minimum gap between 2 adjacent values is " + gap + " "); 
}

答案 1 :(得分:0)

import java.util.*;
public class minGapClass
{
  public static void main(String[] args){
    int[] list = {3, 1, 6, 12, 7};
    int minResult = minGap(list);
    System.out.println(minResult);

}
  public static int minGap(int[] list){

    if (list.length < 2){
        return 0;
    }
    int min = list[1] - list[0];
    for (int i = 0; i < list.length-1; i++){
        if (min > list[i+1] - list[i]){
             min = list[i+1] - list[i];
        } 
    }
    return min;
}
}