LeetCode 题解工作台

统计符合条件长度为 3 的子数组数目

给你一个整数数组 nums ,请你返回长度为 3 的 子数组 的数量,满足第一个数和第三个数的和恰好为第二个数的一半。 子数组 指的是一个数组中连续 非空 的元素序列。 示例 1: 输入: nums = [1,2,1,4,1] 输出: 1 解释: 只有子数组 [1,4,1] 包含 3 个元素且第一个…

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·driven

bolt

答案摘要

我们遍历数组 每个长度为 的子数组,判断第一个数和第三个数的和乘以 是否等于第二个数,若是,答案加 。 遍历结束后,返回答案即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 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
lightbulb

解题思路

方法一:一次遍历

我们遍历数组 nums\textit{nums} 每个长度为 33 的子数组,判断第一个数和第三个数的和乘以 22 是否等于第二个数,若是,答案加 11

遍历结束后,返回答案即可。

时间复杂度 O(n)O(n),其中 nn 为数组 nums\textit{nums} 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
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)
        )
speed

复杂度分析

指标
时间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)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

统计符合条件长度为 3 的子数组数目题解:数组·driven | LeetCode #3392 简单