[LeetCode] 2348. Number of Zero-Filled Subarrays
Given an integer array nums
, return the number of subarrays filled with 0
.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1,3,0,0,2,0,0,4] Output: 6 Explanation: There are 4 occurrences of [0] as a subarray. There are 2 occurrences of [0,0] as a subarray. There is no occurrence of a subarray with a size more than 2 filled with 0. Therefore, we return 6.
Example 2:
Input: nums = [0,0,0,2,0,0] Output: 9 Explanation: There are 5 occurrences of [0] as a subarray. There are 3 occurrences of [0,0] as a subarray. There is 1 occurrence of [0,0,0] as a subarray. There is no occurrence of a subarray with a size more than 3 filled with 0. Therefore, we return 9.
Example 3:
Input: nums = [2,10,2019] Output: 0 Explanation: There is no subarray filled with 0. Therefore, we return 0.
Constraints:
1 <= nums.length <= 105
-109 <= nums[i] <= 109
全 0 子数组的数目。
给你一个整数数组 nums ,返回全部为 0 的 子数组 数目。
子数组 是一个数组中一段连续非空元素组成的序列。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/number-of-zero-filled-subarrays
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这是一道数学题,也可以用动态规划做。我参考了这个帖子。
具体的思路是如果我们当前位置上遇到的是一个 0,我们就把当前这个 0 当做子数组的结尾,来统计以当前这个 0 为结尾的符合题意的子数组有多少。举个例子,比如 [0, 0, 0, 0],我们设一个变量 count 记录当前遇到的连续的 0 的个数
当我们遇到第一个 0 的时候,count = 1, res += count
当我们遇到第二个 0 的时候,count = 2, res += count
这里 count 其实暗含了子数组的个数。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public long zeroFilledSubarray(int[] nums) { 3 long res = 0; 4 int n = nums.length; 5 int count = 0; 6 for (int i = 0; i < n; i++) { 7 if (nums[i] == 0) { 8 count++; 9 res += count; 10 } else { 11 count = 0; 12 } 13 } 14 return res; 15 } 16 }