LeetCode 题解工作台

最小绝对差

给你个整数数组 arr ,其中每个元素都 不相同 。 请你找到所有具有最小绝对差的元素对,并且按升序的顺序返回。 每对元素对 [a,b ] 如下: a , b 均为数组 arr 中的元素 a b - a 等于 arr 中任意两个元素的最小绝对差 示例 1: 输入: arr = [4,2,1,3] 输…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·排序

bolt

答案摘要

根据题目描述,我们需要找出数组 中任意两个元素的最小绝对差,因此我们可以先对数组 排序,随后遍历相邻元素,得到最小绝对差 。 最后我们再遍历相邻元素,找出所有最小绝对差等于 的元素对。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你个整数数组 arr,其中每个元素都 不相同

请你找到所有具有最小绝对差的元素对,并且按升序的顺序返回。

每对元素对 [a,b] 如下:

  • a , b 均为数组 arr 中的元素
  • a < b
  • b - a 等于 arr 中任意两个元素的最小绝对差

 

示例 1:

输入:arr = [4,2,1,3]
输出:[[1,2],[2,3],[3,4]]

示例 2:

输入:arr = [1,3,6,10,15]
输出:[[1,3]]

示例 3:

输入:arr = [3,8,-10,23,19,-4,-14,27]
输出:[[-14,-10],[19,23],[23,27]]

 

提示:

  • 2 <= arr.length <= 10^5
  • -10^6 <= arr[i] <= 10^6
lightbulb

解题思路

方法一:排序

根据题目描述,我们需要找出数组 arrarr 中任意两个元素的最小绝对差,因此我们可以先对数组 arrarr 排序,随后遍历相邻元素,得到最小绝对差 mimi

最后我们再遍历相邻元素,找出所有最小绝对差等于 mimi 的元素对。

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 O(logn)O(\log n)。其中 nn 是数组 arrarr 的长度。

1
2
3
4
5
6
class Solution:
    def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
        arr.sort()
        mi = min(b - a for a, b in pairwise(arr))
        return [[a, b] for a, b in pairwise(arr) if b - a == mi]
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Assessing the candidate's approach to sorting and handling consecutive elements in the array.

  • question_mark

    Looking for clarity in the explanation of the solution's efficiency and correctness.

  • question_mark

    Evaluating how well the candidate optimizes both time and space complexity for large arrays.

warning

常见陷阱

外企场景
  • error

    Not sorting the array before comparing pairs, which could result in incorrect outputs or inefficiency.

  • error

    Failing to handle edge cases such as arrays with only two elements or arrays with larger numbers of elements.

  • error

    Misunderstanding the requirement to return pairs in ascending order or returning them in an unsorted manner.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Consider the case when the array contains negative numbers or is already sorted.

  • arrow_right_alt

    What happens when there are multiple pairs with the same minimum absolute difference?

  • arrow_right_alt

    How would the solution change if the array were unsorted or if elements could repeat?

help

常见问题

外企场景

最小绝对差题解:数组·排序 | LeetCode #1200 简单