LeetCode 题解工作台
最长定差子序列
给你一个整数数组 arr 和一个整数 difference ,请你找出并返回 arr 中最长等差子序列的长度,该子序列中相邻元素之间的差等于 difference 。 子序列 是指在不改变其余元素顺序的情况下,通过删除一些元素或不删除任何元素而从 arr 派生出来的序列。 示例 1: 输入: arr…
3
题型
7
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们可以使用哈希表 来存储以 结尾的最长等差子序列的长度。 遍历数组 ,对于每个元素 ,我们更新 为 $f[x - \textit{difference}] + 1$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个整数数组 arr 和一个整数 difference,请你找出并返回 arr 中最长等差子序列的长度,该子序列中相邻元素之间的差等于 difference 。
子序列 是指在不改变其余元素顺序的情况下,通过删除一些元素或不删除任何元素而从 arr 派生出来的序列。
示例 1:
输入:arr = [1,2,3,4], difference = 1 输出:4 解释:最长的等差子序列是 [1,2,3,4]。
示例 2:
输入:arr = [1,3,5,7], difference = 1 输出:1 解释:最长的等差子序列是任意单个元素。
示例 3:
输入:arr = [1,5,7,8,5,3,4,2,1], difference = -2 输出:4 解释:最长的等差子序列是 [7,5,3,1]。
提示:
1 <= arr.length <= 105-104 <= arr[i], difference <= 104
解题思路
方法一:动态规划
我们可以使用哈希表 来存储以 结尾的最长等差子序列的长度。
遍历数组 ,对于每个元素 ,我们更新 为 。
遍历结束后,我们返回 中的最大值作为答案返回即可。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def longestSubsequence(self, arr: List[int], difference: int) -> int:
f = defaultdict(int)
for x in arr:
f[x] = f[x - difference] + 1
return max(f.values())
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate should demonstrate familiarity with dynamic programming techniques.
- question_mark
They should understand how hash tables are used to optimize subsequence tracking.
- question_mark
The candidate must ensure they can explain the trade-offs between time and space complexity in this approach.
常见陷阱
外企场景- error
Forgetting to account for negative differences when scanning the array.
- error
Overcomplicating the problem by trying to brute force through all possible subsequences.
- error
Not using hash tables efficiently, leading to unnecessary recomputation or slower performance.
进阶变体
外企场景- arrow_right_alt
Consider variations where the difference is zero, which means the subsequence would consist of identical elements.
- arrow_right_alt
Explore scenarios where elements of the array are all unique but can form an arithmetic subsequence with a given difference.
- arrow_right_alt
Test with arrays that have negative and positive numbers mixed, making sure the algorithm handles both directions of differences.