LeetCode 1200. Minimum Absolute Difference
考点 | 难度 |
---|---|
Sorting | Easy |
题目
Given an array of distinct integers arr
, find all pairs of elements with the minimum absolute difference of any two elements.
Return a list of pairs in ascending order(with respect to pairs), each pair [a, b]
follows:
1 a, b are from arr
2 a < b
3 b - a equals to the minimum absolute difference of any two elements in arr
思路
先排序,找到两个相邻数字之间最小的差,再遍历找到符合这个差的数。
答案
public List<List<Integer>> minimumAbsDifference(int[] arr) {
// Sort the original array
Arrays.sort(arr);
List<List<Integer>> answer = new ArrayList();
// Initialize minimum difference as a huge integer in order not
// to miss the absolute difference of the first pair.
int minPairDiff = Integer.MAX_VALUE;
// Traverse the sorted array and calcalute the minimum absolute difference.
for (int i = 0; i < arr.length - 1; ++i) {
minPairDiff = Math.min(minPairDiff, arr[i + 1] - arr[i]);
}
// Traverse the sorted array and check every pair again, if
// the absolute difference equals the minimum difference,
// add this pair to the answer list.
for (int i = 0; i < arr.length - 1; ++i) {
if (arr[i + 1] - arr[i] == minPairDiff) {
answer.add(Arrays.asList(arr[i], arr[i + 1]));
}
}
return answer;
}