Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 2348. Number of Zero-Filled Subarrays #227

Open
Woodyiiiiiii opened this issue Mar 21, 2023 · 0 comments
Open

Leetcode 2348. Number of Zero-Filled Subarrays #227

Woodyiiiiiii opened this issue Mar 21, 2023 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

Woodyiiiiiii commented Mar 21, 2023

这道题很简单,但我的推导过程让我感到有些惊讶和有意思,所以特意开一贴记录下来。

源地址: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,不过前者是三指针,这里是双指针。

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;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant