Skip to content

Latest commit

 

History

History
146 lines (119 loc) · 3.4 KB

File metadata and controls

146 lines (119 loc) · 3.4 KB

中文文档

Description

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 from arr
  • a < b
  • b - a equals to the minimum absolute difference of any two elements in arr

 

Example 1:

Input: arr = [4,2,1,3]
Output: [[1,2],[2,3],[3,4]]
Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.

Example 2:

Input: arr = [1,3,6,10,15]
Output: [[1,3]]

Example 3:

Input: arr = [3,8,-10,23,19,-4,-14,27]
Output: [[-14,-10],[19,23],[23,27]]

 

Constraints:

  • 2 <= arr.length <= 105
  • -106 <= arr[i] <= 106

Solutions

Python3

class Solution:
    def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
        arr.sort()
        ans = []
        mi = inf
        for a, b in pairwise(arr):
            d = b - a
            if d < mi:
                ans = [(a, b)]
                mi = d
            elif d == mi:
                ans.append((a, b))
        return ans

Java

class Solution {
    public List<List<Integer>> minimumAbsDifference(int[] arr) {
        Arrays.sort(arr);
        List<List<Integer>> ans = new ArrayList<>();
        int n = arr.length;
        int mi = Integer.MAX_VALUE;
        for (int i = 0; i < n - 1; ++i) {
            int a = arr[i], b = arr[i + 1];
            int d = b - a;
            if (d < mi) {
                ans.clear();
                ans.add(Arrays.asList(a, b));
                mi = d;
            } else if (d == mi) {
                ans.add(Arrays.asList(a, b));
            }
        }
        return ans;
    }
}

C++

class Solution {
public:
    vector<vector<int>> minimumAbsDifference(vector<int>& arr) {
        sort(arr.begin(), arr.end());
        int mi = INT_MAX;
        int n = arr.size();
        vector<vector<int>> ans;
        for (int i = 0; i < n - 1; ++i) {
            int a = arr[i], b = arr[i + 1];
            int d = b - a;
            if (d < mi) {
                mi = d;
                ans.clear();
                ans.push_back({a, b});
            } else if (d == mi)
                ans.push_back({a, b});
        }
        return ans;
    }
};

Go

func minimumAbsDifference(arr []int) [][]int {
	sort.Ints(arr)
	mi := math.MaxInt32
	var ans [][]int
	for i, a := range arr[:len(arr)-1] {
		b := arr[i+1]
		d := b - a
		if d < mi {
			mi = d
			ans = [][]int{[]int{a, b}}
		} else if d == mi {
			ans = append(ans, []int{a, b})
		}
	}
	return ans
}

...