LeetCode 题解工作台
判断能否形成等差数列
给你一个数字数组 arr 。 如果一个数列中,任意相邻两项的差总等于同一个常数,那么这个数列就称为 等差数列 。 如果可以重新排列数组形成等差数列,请返回 true ;否则,返回 false 。 示例 1: 输入: arr = [3,5,1] 输出: true 解释: 对数组重新排序得到 [1,3,…
2
题型
8
代码语言
3
相关题
当前训练重点
简单 · 数组·排序
答案摘要
我们可以先将数组 排序,然后计算前两项的差值 ,接着遍历数组,判断相邻两项的差是否等于 。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 为数组 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路
题目描述
给你一个数字数组 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
解题思路
方法一:排序 + 遍历
我们可以先将数组 排序,然后计算前两项的差值 ,接着遍历数组,判断相邻两项的差是否等于 。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
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))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.