LeetCode 题解工作台
最长等差数列
给你一个整数数组 nums ,返回 nums 中最长等差子序列的 长度 。 回想一下, nums 的子序列是一个列表 nums[i 1 ], nums[i 2 ], ..., nums[i k ] ,且 0 1 2 k 。并且如果 seq[i+1] - seq[i] ( 0 ) 的值都相同,那么序列…
4
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们定义 表示以 结尾且公差为 的等差数列的最大长度。初始时 ,即每个元素自身都是一个长度为 的等差数列。 > 由于公差可能为负数,且最大差值为 ,因此,我们可以将统一将公差加上 ,这样公差的范围就变成了 $[0, 1000]$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个整数数组 nums,返回 nums 中最长等差子序列的长度。
回想一下,nums 的子序列是一个列表 nums[i1], nums[i2], ..., nums[ik] ,且 0 <= i1 < i2 < ... < ik <= nums.length - 1。并且如果 seq[i+1] - seq[i]( 0 <= i < seq.length - 1) 的值都相同,那么序列 seq 是等差的。
示例 1:
输入:nums = [3,6,9,12] 输出:4 解释: 整个数组是公差为 3 的等差数列。
示例 2:
输入:nums = [9,4,7,2,10] 输出:3 解释: 最长的等差子序列是 [4,7,10]。
示例 3:
输入:nums = [20,1,15,3,10,5,8] 输出:4 解释: 最长的等差子序列是 [20,15,10,5]。
提示:
2 <= nums.length <= 10000 <= nums[i] <= 500
解题思路
方法一:动态规划
我们定义 表示以 结尾且公差为 的等差数列的最大长度。初始时 ,即每个元素自身都是一个长度为 的等差数列。
由于公差可能为负数,且最大差值为 ,因此,我们可以将统一将公差加上 ,这样公差的范围就变成了 。
考虑 ,我们可以枚举 的前一个元素 ,那么公差 ,此时有 ,然后我们更新答案 。
最后返回答案即可。
如果初始时 ,那么我们需要在最后返回答案时加上 。
时间复杂度 ,空间复杂度 。其中 和 分别是数组 的长度以及数组 中元素的最大值与最小值的差值。
class Solution:
def longestArithSeqLength(self, nums: List[int]) -> int:
n = len(nums)
f = [[1] * 1001 for _ in range(n)]
ans = 0
for i in range(1, n):
for k in range(i):
j = nums[i] - nums[k] + 500
f[i][j] = max(f[i][j], f[k][j] + 1)
ans = max(ans, f[i][j])
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n^2) due to scanning all pairs of elements, and space complexity is O(n*d) because each element maintains a hash map of differences to subsequence lengths, where d is the number of unique differences in the array. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Asks about hash map usage for tracking differences
- question_mark
Tests understanding of DP and subsequence extension
- question_mark
Probes for handling large arrays within constraints
常见陷阱
外企场景- error
Not updating the hash map correctly for each difference
- error
Assuming subsequences must be contiguous
- error
Overlooking large differences or negative steps in subsequences
进阶变体
外企场景- arrow_right_alt
Find the longest arithmetic subsequence with a fixed common difference
- arrow_right_alt
Return the actual longest arithmetic subsequence, not just length
- arrow_right_alt
Handle sequences where elements can repeat