LeetCode 题解工作台
区间子数组个数
给你一个整数数组 nums 和两个整数: left 及 right 。找出 nums 中连续、非空且其中最大元素在范围 [left, right] 内的子数组,并返回满足条件的子数组的个数。 生成的测试用例保证结果符合 32-bit 整数范围。 示例 1: 输入: nums = [2,1,4,3],…
2
题型
4
代码语言
3
相关题
当前训练重点
中等 · 双·指针·invariant
答案摘要
题目要我们统计数组 `nums` 中,最大值在区间 $[left, right]$ 范围内的子数组个数。 对于区间 问题,我们可以考虑将其转换为 然后再减去 的问题。也就是说,所有最大元素不超过 的子数组个数,减去所有最大元素不超过 的子数组个数,剩下的就是最大元素在区间 范围内的子数组个数,即题目要求的结果。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给你一个整数数组 nums 和两个整数:left 及 right 。找出 nums 中连续、非空且其中最大元素在范围 [left, right] 内的子数组,并返回满足条件的子数组的个数。
生成的测试用例保证结果符合 32-bit 整数范围。
示例 1:
输入:nums = [2,1,4,3], left = 2, right = 3 输出:3 解释:满足条件的三个子数组:[2], [2, 1], [3]
示例 2:
输入:nums = [2,9,2,5,6], left = 2, right = 8 输出:7
提示:
1 <= nums.length <= 1050 <= nums[i] <= 1090 <= left <= right <= 109
解题思路
方法一:区间计数
题目要我们统计数组 nums 中,最大值在区间 范围内的子数组个数。
对于区间 问题,我们可以考虑将其转换为 然后再减去 的问题。也就是说,所有最大元素不超过 的子数组个数,减去所有最大元素不超过 的子数组个数,剩下的就是最大元素在区间 范围内的子数组个数,即题目要求的结果。
对于本题,我们设计一个函数 ,表示数组 nums 中,最大值不超过 的子数组个数。那么答案为 。函数 的执行逻辑如下:
- 用变量 记录最大值不超过 的子数组的个数,用 记录当前子数组的长度。
- 遍历数组
nums,对于每个元素 ,如果 ,则当前子数组的长度加一,即 ,否则当前子数组的长度重置为 0,即 。然后将当前子数组的长度加到 中,即 。 - 遍历结束,将 返回即可。
时间复杂度 ,空间复杂度 。其中 为数组 nums 的长度。
class Solution:
def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:
def f(x):
cnt = t = 0
for v in nums:
t = 0 if v > x else t + 1
cnt += t
return cnt
return f(right) - f(left - 1)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate demonstrates proficiency with sliding window and two-pointer techniques.
- question_mark
Candidate can clearly explain how the two-pointer technique avoids redundant calculations.
- question_mark
Candidate optimizes their approach to avoid recalculating the maximum for each subarray.
常见陷阱
外企场景- error
Failing to properly track subarray bounds and missing valid subarrays.
- error
Over-complicating the solution with nested loops or redundant calculations.
- error
Not efficiently managing the sliding window and recalculating the maximum for each subarray.
进阶变体
外企场景- arrow_right_alt
What if the subarrays can contain more than one element with the same maximum value?
- arrow_right_alt
What if there were additional constraints on subarray lengths?
- arrow_right_alt
How would the solution change if the input array was sorted?