Sorting is often useful as the first step in your different tasks. The most common task is to make finding things easier, but there are other uses also.
Challenge
Given a list of unsorted numbers, can you find the numbers that have the smallest absolute difference between them? If there are multiple pairs, find them all.
Input Format
There will be two lines of input:
- N-The size of the List
- Array-NNumbers of the List
Output Format
Output the pairs of numbers with the smallest difference. if there are multiple pairs, output all of them in ascending order, all on the same line (consecutively) with just a single space between each pair of numbers. if there's a number which lies in two pair, print it two times (see sample case #3 for explanation ).
Constraints
10 <=N<= 200000
-(107) <=X<= (107), whereXεArray
Array [I]! =Array [J], 0 <=I,J<N, AndI! =J
Question: maintain an arraylist and the minidist variable that records the current minimum distance. Whenever the distance between I and I + 1 is the same as that of minidist, place I in the arraylist; when the distance between the two numbers is smaller than minidist, The arraylist is cleared, I is put in, and minidist is updated. Finally, the answer is output based on arraylist.
The Code is as follows:
1 import java.util.*; 2 3 public class Solution { 4 public static void main(String[] args) { 5 Scanner in = new Scanner(System.in); 6 int n = in.nextInt(); 7 int[] ar = new int[n]; 8 for(int i = 0;i < n;i++) 9 ar[i]= in.nextInt();10 11 Arrays.sort(ar);12 ArrayList<Integer> index = new ArrayList<Integer>();13 int miniDis = Integer.MAX_VALUE;14 for(int i = 0;i < n-1;i++){15 if(ar[i+1]-ar[i] < miniDis){16 index.clear();17 index.add(i);18 miniDis = ar[i+1]-ar[i];19 }20 else if(ar[i+1]-ar[i]==miniDis)21 index.add(i);22 }23 for(int i:index){24 System.out.printf("%d %d ", ar[i],ar[i+1]);25 }26 System.out.println();27 28 }29 }