You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
class Solution {
public long zeroFilledSubarray(int[] nums) {
long ans = 0;
int start = -1;
for (int i = 0; i < nums.length; ++i) {
if (nums[i] == 0) {
start = start == -1 ? i : start;
ans += (i - start + 1);
} else {
start = -1;
}
}
return ans;
}
}
The text was updated successfully, but these errors were encountered:
这道题很简单,但我的推导过程让我感到有些惊讶和有意思,所以特意开一贴记录下来。
源地址:2348. Number of Zero-Filled Subarrays
我的想法:
https://leetcode.com/problems/number-of-zero-filled-subarrays/solutions/3321927/java-prefix-sum-hash-o-n-time/?orderBy=hot
不放代码了。思维过程看上链接。
首先看题目条件,先反问自己,为什么是要0的subarray?这样目的是要提醒自己利用好题目条件。接着想到这是prefix sum类型的题目,但意识到麻烦的是如何排除正负数相加为0的子数组的情况。进而继续利用题目条件结合Prefix Sum性质,因为数组内数字只有两种情况,非零数是多少不重要,只要非零即可,所以可以设置这些非零数为-1,从而有效排除情况,直接利用prefix sum。
第二种方法类似#220,不过前者是三指针,这里是双指针。
The text was updated successfully, but these errors were encountered: