给你一个整数数组 nums ,返回全部为 0 的 子数组 数目。
子数组 是一个数组中一段连续非空元素组成的序列。
https://leetcode.cn/problems/number-of-zero-filled-subarrays/description/
- 滑动窗口两种形式:for循环right每次循环一定++;while循环right每次循环不一定++
- 等差数列
/*
* Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
*/
package com.huawei.prac;
class Solution5th {
public static void main(String[] args) {
int[] nums = {1, 3, 0, 0, 2, 0, 0, 4};
System.out.println(zeroFilledSubarray(nums));
System.out.println(zeroFilledSubarray(new int[] {0, 0, 0, 2, 0, 0})); // 9
}
/**
* 2348. 全 0 子数组的数目[滑动窗口]
*
* @param nums
* @return
*/
public static long zeroFilledSubarray(int[] nums) {
long maxSub = 0;
long left = -1;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
maxSub += i - left;
} else {
left = i;
}
}
return maxSub;
}
}