LeetCode 题解工作台
统计符合条件长度为 3 的子数组数目
给你一个整数数组 nums ,请你返回长度为 3 的 子数组 的数量,满足第一个数和第三个数的和恰好为第二个数的一半。 子数组 指的是一个数组中连续 非空 的元素序列。 示例 1: 输入: nums = [1,2,1,4,1] 输出: 1 解释: 只有子数组 [1,4,1] 包含 3 个元素且第一个…
1
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·driven
答案摘要
我们遍历数组 每个长度为 的子数组,判断第一个数和第三个数的和乘以 是否等于第二个数,若是,答案加 。 遍历结束后,返回答案即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路
题目描述
给你一个整数数组 nums ,请你返回长度为 3 的 子数组 的数量,满足第一个数和第三个数的和恰好为第二个数的一半。
子数组 指的是一个数组中连续 非空 的元素序列。
示例 1:
输入:nums = [1,2,1,4,1]
输出:1
解释:
只有子数组 [1,4,1] 包含 3 个元素且第一个和第三个数字之和是中间数字的一半。number.
示例 2:
输入:nums = [1,1,1]
输出:0
解释:
[1,1,1] 是唯一长度为 3 的子数组,但第一个数和第三个数的和不是第二个数的一半。
提示:
3 <= nums.length <= 100-100 <= nums[i] <= 100
解题思路
方法一:一次遍历
我们遍历数组 每个长度为 的子数组,判断第一个数和第三个数的和乘以 是否等于第二个数,若是,答案加 。
遍历结束后,返回答案即可。
时间复杂度 ,其中 为数组 的长度。空间复杂度 。
class Solution:
def countSubarrays(self, nums: List[int]) -> int:
return sum(
(nums[i - 1] + nums[i + 1]) * 2 == nums[i] for i in range(1, len(nums) - 1)
)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) because each subarray of length three is checked once. Space complexity is O(1) since only a counter is used, and no additional data structures grow with input size. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Check whether you are correctly identifying subarrays of exactly length three.
- question_mark
Consider off-by-one errors when looping over the array.
- question_mark
Expect clarification on handling sums that require integer division carefully.
常见陷阱
外企场景- error
Including subarrays of length other than three, which violates the condition.
- error
Using incorrect indices leading to out-of-bounds errors.
- error
Forgetting integer division when comparing sums to half the middle element.
进阶变体
外企场景- arrow_right_alt
Count subarrays of length k where a custom sum condition holds for specific positions.
- arrow_right_alt
Find subarrays where the sum of first and last elements is equal to the middle element without division.
- arrow_right_alt
Modify the problem to return the actual valid subarrays instead of just counting them.