美文网首页
全 0 子数组的数目 ^.^ 2022/08/17

全 0 子数组的数目 ^.^ 2022/08/17

作者: 佛说子曰道道 | 来源:发表于2022-08-16 15:43 被阅读0次

https://leetcode.cn/problems/number-of-zero-filled-subarrays/
看完示例之后的第一反应:先找这个数组内最长的由0组成的子数组。然后再去逐个拆分这些子数组,最后加到结果中。
只是其中有个点,可能初学者不太容易get到,比如0000这个数组。
如果取一个:索引从0到3,长度为1,一共有4个
如果取两个:索引从0到2,长度为2,一共有3个
如果取三个:索引从0到1,长度为3,一共有2个
如果取四个:索引从0到0,长度为4,一共有1个
所以子数组有n个0,就是有0+1+2+……+n。
最后代码如下:

    public long zeroFilledSubarray(int[] nums) {
        long count = 0;
        int tempCount = 0;
        for (int num : nums) {
            if (num == 0) {
                tempCount++;
            } else {
                while (tempCount != 0) {
                    count = count + (tempCount--);
                }
            }
        }
        while (tempCount != 0) {
            count = count + (tempCount--);
        }
        return count;
    }

相关文章

网友评论

      本文标题:全 0 子数组的数目 ^.^ 2022/08/17

      本文链接:https://www.haomeiwen.com/subject/rlgjgrtx.html