LeetCode 题解工作台

判断能否形成等差数列

给你一个数字数组 arr 。 如果一个数列中,任意相邻两项的差总等于同一个常数,那么这个数列就称为 等差数列 。 如果可以重新排列数组形成等差数列,请返回 true ;否则,返回 false 。 示例 1: 输入: arr = [3,5,1] 输出: true 解释: 对数组重新排序得到 [1,3,…

category

2

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·排序

bolt

答案摘要

我们可以先将数组 排序,然后计算前两项的差值 ,接着遍历数组,判断相邻两项的差是否等于 。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 为数组 的长度。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个数字数组 arr

如果一个数列中,任意相邻两项的差总等于同一个常数,那么这个数列就称为 等差数列

如果可以重新排列数组形成等差数列,请返回 true ;否则,返回 false

 

示例 1:

输入:arr = [3,5,1]
输出:true
解释:对数组重新排序得到 [1,3,5] 或者 [5,3,1] ,任意相邻两项的差分别为 2 或 -2 ,可以形成等差数列。

示例 2:

输入:arr = [1,2,4]
输出:false
解释:无法通过重新排序得到等差数列。

 

提示:

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

解题思路

方法一:排序 + 遍历

我们可以先将数组 arr\textit{arr} 排序,然后计算前两项的差值 dd,接着遍历数组,判断相邻两项的差是否等于 dd

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 O(logn)O(\log n)。其中 nn 为数组 arr\textit{arr} 的长度。

1
2
3
4
5
6
class Solution:
    def canMakeArithmeticProgression(self, arr: List[int]) -> bool:
        arr.sort()
        d = arr[1] - arr[0]
        return all(b - a == d for a, b in pairwise(arr))
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Focus on transforming the array to detect uniform differences using sorting.

  • question_mark

    Expect candidates to handle edge cases where negative or large numbers appear.

  • question_mark

    Watch for efficient single-pass verification after sorting without unnecessary data structures.

warning

常见陷阱

外企场景
  • error

    Skipping the sorting step and comparing non-consecutive elements directly.

  • error

    Not checking for arrays with length exactly 2, which are always valid progressions.

  • error

    Assuming the array is already in order and missing potential reordering needs.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Determine the minimal number of swaps needed to convert the array into an arithmetic progression.

  • arrow_right_alt

    Check if the array forms a geometric progression instead of arithmetic.

  • arrow_right_alt

    Handle arrays with floating point numbers and verify approximate equality within a tolerance.

help

常见问题

外企场景

判断能否形成等差数列题解:数组·排序 | LeetCode #1502 简单