Finding out the minimum difference between elements in an array

前端 未结 8 654
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-08 01:02

I have an integer array with some finite number of values. My job is to find the minimum difference between any two elements in the array.

Consider that the array co

8条回答
  •  清歌不尽
    2020-12-08 01:18

    The minimum difference will be one of the differences from among the consecutive pairs in sorted order. Sort the array, and go through the pairs of adjacent numbers looking for the smallest difference:

    int[] a = new int[] {4, 9, 1, 32, 13};
    Arrays.sort(a);
    int minDiff = a[1]-a[0];
    for (int i = 2 ; i != a.length ; i++) {
        minDiff = Math.min(minDiff, a[i]-a[i-1]);
    }
    System.out.println(minDiff);
    

    This prints 3.

提交回复
热议问题