3392.统计符合条件长度为 3 的子数组数目:一次遍历模拟

【LetMeFly】3392.统计符合条件长度为 3 的子数组数目:一次遍历模拟

力扣题目链接:https://leetcode.cn/problems/count-subarrays-of-length-three-with-a-condition/

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

解题方法:一次遍历模拟

用变量$i$从第三个元素开始向后遍历数组,若$(nums[i] + nums[i - 2]) * 2 == nums[i - 1]$,则答案数量加一。

  • 时间复杂度$O(len(nums))$
  • 空间复杂度$O(1)$

AC代码

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
* @Author: LetMeFly
* @Date: 2025-04-27 23:47:30
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-04-27 23:48:38
*/
class Solution {
public:
int countSubarrays(vector<int>& nums) {
int ans = 0;
for (int i = 2; i < nums.size(); i++) {
ans += (nums[i] + nums[i - 2]) * 2 == nums[i - 1];
}
return ans;
}
};

Python

1
2
3
4
5
6
7
8
9
10
11
'''
Author: LetMeFly
Date: 2025-04-27 23:49:08
LastEditors: LetMeFly.xyz
LastEditTime: 2025-04-27 23:49:26
'''
from typing import List

class Solution:
def countSubarrays(self, nums: List[int]) -> int:
return sum((nums[i - 2] + nums[i]) * 2 == nums[i - 1] for i in range(2, len(nums)))

Golang

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/*
* @Author: LetMeFly
* @Date: 2025-04-27 23:49:15
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-04-27 23:52:54
* @Description: AC,100.00%,95.45%
*/
package main

func countSubarrays(nums []int) (ans int) {
for i := 2; i < len(nums); i++ {
if (nums[i] + nums[i - 2]) * 2 == nums[i - 1] {
ans++
}
}
return
}

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/*
* @Author: LetMeFly
* @Date: 2025-04-27 23:49:11
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-04-27 23:50:25
*/
class Solution {
public int countSubarrays(int[] nums) {
int ans = 0;
for (int i = 2; i < nums.length; i++) {
if ((nums[i - 2] + nums[i]) * 2 == nums[i - 1]) {
ans++;
}
}
return ans;
}
}

同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~

千篇源码题解已开源


3392.统计符合条件长度为 3 的子数组数目:一次遍历模拟
https://blog.letmefly.xyz/2025/04/29/LeetCode 3392.统计符合条件长度为3的子数组数目/
作者
发布于
2025年4月29日
许可协议