LeetCode 题解工作台
绝对差不超过限制的最长连续子数组
给你一个整数数组 nums ,和一个表示限制的整数 limit ,请你返回最长连续子数组的长度,该子数组中的任意两个元素之间的绝对差必须小于或者等于 limit 。 示例 1: 输入: nums = [8,2,4,7], limit = 4 输出: 2 解释: 所有子数组如下: [8] 最大绝对差 …
6
题型
5
代码语言
3
相关题
当前训练重点
中等 · 滑动窗口(状态滚动更新)
答案摘要
我们可以枚举每个位置作为子数组的右端点,找到其对应的最靠左的左端点,满足区间内中最大值与最小值的差值不超过 。过程中,我们用有序集合维护窗口内的最大值和最小值。 时间复杂度 $O(n \times \log n)$,空间复杂度 。其中 是数组 `nums` 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 滑动窗口(状态滚动更新) 题型思路
题目描述
给你一个整数数组 nums ,和一个表示限制的整数 limit,请你返回最长连续子数组的长度,该子数组中的任意两个元素之间的绝对差必须小于或者等于 limit。
示例 1:
输入:nums = [8,2,4,7], limit = 4 输出:2 解释:所有子数组如下: [8] 最大绝对差 |8-8| = 0 <= 4. [8,2] 最大绝对差 |8-2| = 6 > 4. [8,2,4] 最大绝对差 |8-2| = 6 > 4. [8,2,4,7] 最大绝对差 |8-2| = 6 > 4. [2] 最大绝对差 |2-2| = 0 <= 4. [2,4] 最大绝对差 |2-4| = 2 <= 4. [2,4,7] 最大绝对差 |2-7| = 5 > 4. [4] 最大绝对差 |4-4| = 0 <= 4. [4,7] 最大绝对差 |4-7| = 3 <= 4. [7] 最大绝对差 |7-7| = 0 <= 4. 因此,满足题意的最长子数组的长度为 2 。
示例 2:
输入:nums = [10,1,2,4,7,2], limit = 5 输出:4 解释:满足题意的最长子数组是 [2,4,7,2],其最大绝对差 |2-7| = 5 <= 5 。
示例 3:
输入:nums = [4,2,2,2,4,4,2,2], limit = 0 输出:3
提示:
1 <= nums.length <= 1051 <= nums[i] <= 1090 <= limit <= 109
解题思路
方法一:有序集合 + 滑动窗口
我们可以枚举每个位置作为子数组的右端点,找到其对应的最靠左的左端点,满足区间内中最大值与最小值的差值不超过 。过程中,我们用有序集合维护窗口内的最大值和最小值。
时间复杂度 ,空间复杂度 。其中 是数组 nums 的长度。
class Solution:
def longestSubarray(self, nums: List[int], limit: int) -> int:
sl = SortedList()
ans = j = 0
for i, x in enumerate(nums):
sl.add(x)
while sl[-1] - sl[0] > limit:
sl.remove(nums[j])
j += 1
ans = max(ans, i - j + 1)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Look for understanding of sliding window techniques.
- question_mark
Evaluate how efficiently the candidate handles window adjustments and tracking of max/min values.
- question_mark
Assess the ability to explain why O(n) time complexity is achievable.
常见陷阱
外企场景- error
Failing to update the window correctly when the absolute difference exceeds the limit.
- error
Using inefficient data structures for tracking max/min values, leading to suboptimal time complexity.
- error
Not handling edge cases such as very small arrays or large limit values properly.
进阶变体
外企场景- arrow_right_alt
Allowing the subarray to contain negative numbers and adjusting the absolute difference condition.
- arrow_right_alt
Extending the problem to find the sum of elements in the longest subarray that meets the condition.
- arrow_right_alt
Modifying the condition to check for differences in specific positions within the subarray instead of all pairs.