解题思路
每次操作的都是同一个比特位,可以把每一位单独看。
需要子数组的数的比特位为1的数为偶数。
跟异或操作的 相同为零 不同为一 相似
把区间内所以比特位异或起来为零
利用前缀异或和 ,问题相当于在求 s 中有多少对相同的数字。
每两个相同的数字之间形成了异或为零的美丽子数组
n个相同的数字可以组成0+1+……+n-1个子数组
class Solution {
public:
long long beautifulSubarrays(vector<int>& nums) {
int s[100005] = {0};
long long sum[100005] = {0}, ret = 0;
map<int, int> mp;
mp[0] = 1;
for (int i = 0; i < nums.size(); i++)
{
s[i + 1] = s[i] ^ nums[i];
mp[s[i + 1]]++;
}
for(int i = 1; i <= 100000; i ++ ) sum[i + 1] = i + sum[i];
for (auto v : mp)
{
ret += sum[v.second];
}
mp.clear();
return ret;
}
};