想法大致和以下答案一樣,但有點複雜(例如n個連續零,就加上n + n - 1 + n - 2 + ... + 0)
思路
走過所有數字
每次遇到0,計數器+1,result直接加上當前zero的數量
因為如果00,subarray有1+2個;000,subarray有1+2+3個,以此類推
Code
classSolution{publiclongzeroFilledSubarray(int[] nums){long res =0;int count =0;// Consecutive zeros// Go through all numbersfor(int i =0; i < nums.length;++i){if(nums[i]==0){// 1 more zero++count;
res += count;}else{
count =0;}}return res;}}