-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimumDifference.java
More file actions
48 lines (36 loc) · 1.3 KB
/
Copy pathMinimumDifference.java
File metadata and controls
48 lines (36 loc) · 1.3 KB
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
44
45
46
47
48
package array;
import java.util.*;
/**
* Question: Given an array of distinct integers, find all pairs of elements where the difference between the two elements
* is the smallest among all pairs in the array
* Return these pairs in ascending order, where each pair is represented by [a, b] such that a, b are elements from the
* array and a < b. The difference between a and b should be the smallest
*/
public class MinimumDifference {
public static void main(String[] args) {
int[] a = {12, 9, 8, 2, 11, 4, 5, 3};
List<List<Integer>> res = minDiffPairs(a);
System.out.println(res);
}
static List<List<Integer>> minDiffPairs(int[] a) {
List<List<Integer>> ans = new ArrayList<>();
Arrays.sort(a);
int n = a.length;
int minDiff = Integer.MAX_VALUE;
for (int i = 1; i < n; i++) {
// if(a[i] - a[i-1] < minDiff){
// minDiff = a[i] - a[i-1];
// }
minDiff = Math.min(minDiff, a[i] - a[i - 1]);
}
for (int i = 1; i < n; i++) {
if (a[i] - a[i - 1] == minDiff) {
List<Integer> temp = new ArrayList<>();
temp.add(a[i - 1]);
temp.add(a[i]);
ans.add(temp);
}
}
return ans;
}
}