美文网首页
LeetCode 1200. Minimum Absolute

LeetCode 1200. Minimum Absolute

作者: LiNGYu_NiverSe | 来源:发表于2020-11-21 01:45 被阅读0次

    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 <= 10^5
    • -10^6 <= arr[i] <= 10^6

    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()将元素配对。只要我们找到一对的差等于最小绝对差,就将其加到我们的结果中。

    相关文章

      网友评论

          本文标题:LeetCode 1200. Minimum Absolute

          本文链接:https://www.haomeiwen.com/subject/qaksiktx.html