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
a, b
are fromarr
a < b
b - a
equals to the minimum absolute difference of any two elements inarr
Example 1:
Input: arr = [4,2,1,3]
Output: [[1,2],[2,3],[3,4]]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class MinimumAbsoluteDifference {public static void main(String[] args) {int[] arr = { 4, 2, 1, 3 };List<List<Integer>> res = minimumAbsDifference(arr);System.out.println(Arrays.asList(res));}static List<List<Integer>> minimumAbsDifference(int[] arr) {Arrays.sort(arr);int min1 = Integer.MAX_VALUE;List<List<Integer>> res = new ArrayList<List<Integer>>();for (int i = 1; i < arr.length; i++) {min1 = Math.min(arr[i] - arr[i - 1], min1);}for (int i = 1; i < arr.length; i++) {if (arr[i] - arr[i - 1] == min1) {List<Integer> x = new ArrayList<Integer>();x.add(arr[i - 1]);x.add(arr[i]);res.add(x);}}return res;}}
C++
#include <bits/stdc++.h>using namespace std;vector<vector<int>> minimumAbsDifference(vector<int> &arr){sort(arr.begin(), arr.end());int min1 = INT_MAX;vector<vector<int>> res;for (int i = 1; i < arr.size(); i++)min1 = min(arr[i] - arr[i - 1], min1);for (int i = 1; i < arr.size(); i++){if (arr[i] - arr[i - 1] == min1){vector<int> x;x.push_back(arr[i - 1]);x.push_back(arr[i]);res.push_back(x);}}return res;}int main(){vector<int> arr = {4, 2, 1, 3};vector<vector<int>> res = minimumAbsDifference(arr);cout << "[";for (int i = 0; i < res.size(); i++){cout << "[";for (int j = 0; j < res[i].size(); j++){cout << res[i][j];if (j != res[i].size() - 1)cout << ",";}cout << "]";if (i != res.size() - 1)cout << ",";}cout << "]";return 0;}
No comments:
Post a Comment