Finding out the minimum difference between elements in an array

前端 未结 8 637
爱一瞬间的悲伤
爱一瞬间的悲伤 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:13

    In Python 3 this problem can be simplified by using the module itertools which gives the combinations available for a list. From that list we can find the sum of each combination and find the minimum of those values.

    import itertools
    
    arr = [4, 9, 1, 32, 13]
    
    if len(arr) > 1:
        min_diff = abs(arr[0] - arr[1])
    else:
        min_diff = 0
    
    for n1, n2 in itertools.combinations(arr, 2): # Get the combinations of numbers
        diff = abs(n1-n2) # Find the absolute difference of each combination
        if min_diff > diff:
            min_diff = diff # Replace incase a least differnce found
    
    print(min_diff)  
    
    0 讨论(0)
  • 2020-12-08 01:17

    sharing the simplest solution.

    function FindMin(arr) {
    
        //sort the array in increasing order
    
        arr.sort((a,b) => {
           return a-b;
        });
    
        let min = arr[1]-arr[0];
    
        let n = arr.length;
    
        for (var i=0;i<n;i++) {
    
          let m = arr[i+1] - arr[i];
          if(m < min){
            m = min;
          }
        }
    
        return m; // minimum difference.
      }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-08 01:18

    While all the answers are correct, I wanted to show the underlying algorithm responsible for n log n run time. The divide and conquer way of finding the minimum distance between the two points or finding the closest points in a 1-D plane.

    The general algorithm:

    • Let m = median(S).
    • Divide S into S1, S2 at m.
    • δ1 = Closest-Pair(S1).
    • δ2 = Closest-Pair(S2).
    • δ12 is minimum distance across the cut.
    • Return δ = min(δ1, δ2, δ12).

    Here is a sample I created in Javascript:

    // Points in 1-D
    var points = [4, 9, 1, 32, 13];
    
    var smallestDiff;
    
    function mergeSort(arr) {
      if (arr.length == 1)
        return arr;
    
      if (arr.length > 1) {
        let breakpoint = Math.ceil((arr.length / 2));
        // Left list starts with 0, breakpoint-1
        let leftList = arr.slice(0, breakpoint);
        // Right list starts with breakpoint, length-1
        let rightList = arr.slice(breakpoint, arr.length);
    
        // Make a recursive call
        leftList = mergeSort(leftList);
        rightList = mergeSort(rightList);
    
        var a = merge(leftList, rightList);
        return a;
      }
    }
    
    function merge(leftList, rightList) {
      let result = [];
      while (leftList.length && rightList.length) {
        // Sorting the x coordinates
        if (leftList[0] <= rightList[0]) {
          result.push(leftList.shift());
        } else {
          result.push(rightList.shift());
        }
      }
    
      while (leftList.length)
        result.push(leftList.shift());
    
      while (rightList.length)
        result.push(rightList.shift());
    
      let diff;
      if (result.length > 1) {
        diff = result[1] - result[0];
      } else {
        diff = result[0];
      }
    
      if (smallestDiff) {
        if (diff < smallestDiff)
          smallestDiff = diff;
      } else {
        smallestDiff = diff;
      }
      return result;
    }
    
    mergeSort(points);
    
    console.log(`Smallest difference: ${smallestDiff}`);

    0 讨论(0)
  • 2020-12-08 01:20

    I would put them in a heap in O(nlogn) then pop one by one and get the minimum difference between every element that I pop. Finally I would have the minimum difference. However, there might be a better solution.

    0 讨论(0)
  • 2020-12-08 01:21

    You can take advantage of the fact that you are considering integers to make a linear algorithm:

    1. First pass: compute the maximum and the minimum
    2. Second pass: allocate a boolean array of length (max - min + 1), false initialized, and change the (value - min)th value to true for every value in the array
    3. Third pass: compute the differences between the indexes of the true valued entries of the boolean array.
    0 讨论(0)
提交回复
热议问题