Leetcode 1200. Minimum Absolute Difference
Given an array of distinct integers arr
, find all pairs of elements with the minimum absolute difference of any two elements. Each pair arr[i], arr[j]
must be in the format [arr[i], arr[j]]
with arr[i] < arr[j]
.
Return a list of pairs in ascending order(with respect to pairs), each pair [a, b]
follows
a < b
a
= arr[i]b
= arr[j]|a - b|
== minimum absolute difference of any two elementsHere is the C++ solution to the problem:
#include <vector>
#include <algorithm>
#include <cmath>
std::vector<std::vector<int>> minimumAbsDifference(std::vector<int>& arr) {
// Sort the array
std::sort(arr.begin(), arr.end());
// Initialize the minimum difference as a large value
int min_diff = INT_MAX;
// Compute the minimum absolute difference
for (size_t i = 0; i < arr.size() - 1; ++i) {
min_diff = std::min(min_diff, arr[i+1] - arr[i]);
}
// Collect all pairs with the minimum absolute difference
std::vector<std::vector<int>> result;
for (size_t i = 0; i < arr.size() - 1; ++i) {
if (arr[i+1] - arr[i] == min_diff) {
result.push_back({arr[i], arr[i+1]});
}
}
return result;
}
min_diff
to the maximum possible integer value.min_diff
to be the minimum of the current min_diff
and the difference between each pair of consecutive elements.min_diff
.O(n log n)
.O(n)
.O(n)
.Thus, the overall time complexity of the solution is O(n log n)
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?