LeetCode 1200. Minimum Absolute Difference (Easy)

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容