LeetCode 1200. Minimum Absolute

2020-11-21  本文已影响0人  LiNGYu_NiverSe

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

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:

Solution:

class Solution:
    def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
        arr.sort()                                            
        min_abs = min((j-i) for i, j in zip(arr,arr[1:]))
        return [[i, j] for i, j in zip(arr, arr[1:]) if j-i == min_abs]

First, we need to sort the arr so that we can only compare each adjacent element to find the minimum absolute difference. Then we use zip() to make elements to pairs. As long as we find the difference of each pair is equal to the minimum absolute difference, we add it to our result.
首先,我们需要对arr进行排序,以便我们只用比较每个相邻元素来找到最小绝对差。然后,我们使用zip()将元素配对。只要我们找到一对的差等于最小绝对差,就将其加到我们的结果中。

上一篇下一篇

猜你喜欢

热点阅读