LeetCode 题解工作台
最长交替子数组
给你一个下标从 0 开始的整数数组 nums 。如果 nums 中长度为 m 的子数组 s 满足以下条件,我们称它是一个 交替子数组 : m 大于 1 。 s 1 = s 0 + 1 。 下标从 0 开始的子数组 s 与数组 [s 0 , s 1 , s 0 , s 1 ,...,s (m-1) %…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·结合·enumeration
答案摘要
我们可以枚举子数组的左端点 ,对于每个 ,我们需要找到最长的满足条件的子数组。我们可以从 开始向右遍历,每次遇到相邻元素差值不满足交替条件时,我们就找到了一个满足条件的子数组。我们可以用一个变量 来记录当前元素的差值应该是 还是 ,如果当前元素的差值应该是 ,那么我们就将 取反。当我们找到一个满足条件的子数组 时,我们更新答案为 $\max(ans, j - i + 1)$。 时间复杂度…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·结合·enumeration 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums 。如果 nums 中长度为 m 的子数组 s 满足以下条件,我们称它是一个 交替子数组 :
m大于1。s1 = s0 + 1。- 下标从 0 开始的子数组
s与数组[s0, s1, s0, s1,...,s(m-1) % 2]一样。也就是说,s1 - s0 = 1,s2 - s1 = -1,s3 - s2 = 1,s4 - s3 = -1,以此类推,直到s[m - 1] - s[m - 2] = (-1)m。
请你返回 nums 中所有 交替 子数组中,最长的长度,如果不存在交替子数组,请你返回 -1 。
子数组是一个数组中一段连续 非空 的元素序列。
示例 1:
[2,3],[3,4],[3,4,3] 和 [3,4,3,4]。最长的子数组为 [3,4,3,4],长度为 4。
示例 2:
[4,5] 和 [5,6] 是仅有的两个交替子数组。它们长度都为 2 。
提示:
2 <= nums.length <= 1001 <= nums[i] <= 104
解题思路
方法一:枚举
我们可以枚举子数组的左端点 ,对于每个 ,我们需要找到最长的满足条件的子数组。我们可以从 开始向右遍历,每次遇到相邻元素差值不满足交替条件时,我们就找到了一个满足条件的子数组。我们可以用一个变量 来记录当前元素的差值应该是 还是 ,如果当前元素的差值应该是 ,那么我们就将 取反。当我们找到一个满足条件的子数组 时,我们更新答案为 。
时间复杂度 ,其中 是数组的长度。我们需要枚举子数组的左端点 ,对于每个 ,我们需要 的时间来找到最长的满足条件的子数组。空间复杂度 。
class Solution:
def alternatingSubarray(self, nums: List[int]) -> int:
ans, n = -1, len(nums)
for i in range(n):
k = 1
j = i
while j + 1 < n and nums[j + 1] - nums[j] == k:
j += 1
k *= -1
if j - i + 1 > 1:
ans = max(ans, j - i + 1)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity can be O(n) where n is the length of the array, depending on the approach used to detect and count alternating subarrays. Space complexity is O(1) since we are not using extra space aside from counters and temporary variables. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate understands the pattern of alternating subarrays.
- question_mark
The candidate can efficiently loop through the array without unnecessary complexity.
- question_mark
Candidate considers edge cases such as no valid alternating subarrays.
常见陷阱
外企场景- error
Not handling the case where no alternating subarrays exist, leading to an incorrect result.
- error
Overcomplicating the solution with extra loops or unnecessary calculations.
- error
Failing to properly track the maximum length of alternating subarrays.
进阶变体
外企场景- arrow_right_alt
Consider optimizing the approach for larger arrays.
- arrow_right_alt
Extend the problem to find alternating subarrays with specific length constraints.
- arrow_right_alt
Alter the problem to return the longest alternating subarray itself, not just the length.