Given an array of distinct integers
Return a list of pairs in ascending order(with respect to pairs), each pair
Example 1:
Example 2:
Example 3:
Solution
There are many solutions to the problem.
Solution 1: Brute Force
Time Complexity : O(n2)
Solution 2: Sorting
Time Complexity : O(nlogn)
Code
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
import java.util.*; public class AbsoluteDifference { public static void main(String[] args) { int [] arr= {3,8,-10,23,19,-4,-14,27}; System.out.println(new AbsoluteDifference().minimumAbsDifference(arr)); } public List<List<Integer>> minimumAbsDifference(int[] arr) { List<List<Integer>> result = new ArrayList<List<Integer>>(); Arrays.sort(arr); int minDiff = Integer.MAX_VALUE; for (int i = 0; i < arr.length - 1; i++) { int tempDiff = arr[i + 1] - arr[i]; minDiff = Math.min(minDiff, tempDiff); } for (int i = 0; i < arr.length - 1; i++) { int tempDiff = arr[i + 1] - arr[i]; if (tempDiff == minDiff) { List<Integer> list = new ArrayList<Integer>(); list.add(arr[i]); list.add(arr[i + 1]); result.add(list); } } return result; } } |
We acknowledge you to write a comment if you have a better solution or having any doubt on the above topic.