-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinAbsDifference.java
More file actions
35 lines (25 loc) · 1001 Bytes
/
Copy pathMinAbsDifference.java
File metadata and controls
35 lines (25 loc) · 1001 Bytes
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
import java.util.*;
class MinAbsDifference {
public List<List<Integer>> minimumAbsDifference(int[] arr) {
//first we will sort the list so that we can find the minimum abs difference
//scan numbers next to each other to find the minimum difference
//scan again to collect all pairs with that difference
Arrays.sort(arr);
//make a new list for the result
List<List<Integer>> res = new ArrayList<>();
//initialize minimum difference
int minDiff = Integer.MAX_VALUE;
//find minimum difference
for(int i = 1; i < arr.length; i++){
int currDiff = arr[i] - arr[i-1];
minDiff = Math.min(currDiff, minDiff);
}
//now we will collect pairs with the minimum difference
for(int i = 1; i < arr.length; i++){
if(arr[i] - arr[i-1] == minDiff){
res.add(Arrays.asList(arr[i-1], arr[i]));
}
}
return res;
}
}