Finding out the minimum difference between elements in an array

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

    This is actually a restatement of the closest-pair problem in one-dimension. https://en.wikipedia.org/wiki/Closest_pair_of_points_problem http://www.cs.umd.edu/~samir/grant/cp.pdf

    As the Wikipedia article cited below points out, the best decision-tree model of this problem also runs in Ω(nlogn) time.

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

    The given problem can easily be solved in O(n) time. Look at the following code that I wrote.

        import java.util.Scanner;
        public class Solution {
        public static void main(String [] args) {
            Scanner input = new Scanner(System.in);
            int i, minDistance = 999999;
            boolean flag = false;
            int capacity = input.nextInt();
            int arr[] = new int[capacity];
            for (i = 0; i < capacity; i++) {
                arr[i] = input.nextInt();
            }
    
            int firstElement = input.nextInt();
            int secondElement = input.nextInt();
    
            int prev = 0;
    
            for (i = 0; i < capacity; i++) {
                if (arr[i] == firstElement || arr[i] == secondElement) {
                    prev = i;
                    break;
                }
            }
    
            for (; i < capacity; i++) {
                if(arr[i] == firstElement || arr[i] == secondElement) {
                    if(arr[i] != arr[prev] && minDistance > Math.abs(i - prev)) {
                        minDistance = Math.abs(i - prev);
                        flag = true;
                        prev = i;
                    } else {
                        prev = i;
                    }
                }
            }
    
            if(flag)
                System.out.println(minDistance);
            else
                System.out.println("-1");
        }
    }
    
    0 讨论(0)
提交回复
热议问题