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 2588. Count the Number of Beautiful Subarrays #224

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

Leetcode 2588. Count the Number of Beautiful Subarrays #224

Woodyiiiiiii opened this issue Mar 15, 2023 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

推理一步步来,首先关键是所谓的“operation”,显然不可能找到每个数值对相同的二进制1然后相减,所以一定要将这个条件简化一下。

那么基本上是位运算了,既然是同位的1,一开始我想的是&与。但细细转换下思维,两个数会消除同位1,这不就是^异或吗。所以这个难点就可以转换成求所有连续子数组使得他们的异或结果为0

这种连续子数组模型的解法,排除了滑动窗口后,就想到用前缀和Map。这种类似的题目还有:

class Solution {
    public long beautifulSubarrays(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, 1);
        int tmp = 0;
        long ans = 0;
        for (int num : nums) {
            tmp ^= num;
            if (map.containsKey(tmp)) {
                ans += map.get(tmp);
            }
            map.put(tmp, map.getOrDefault(tmp, 0) + 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