Skip to content

Commit 3b6208a

Browse files
committed
feat: 2588. Count the Number of Beautiful Subarrays, 前缀和+hash
1 parent 6c8cae5 commit 3b6208a

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
5+
3, 1, 2 => 11, 01, 10
6+
4, 3, 1, 2, 4 => 100, 11, 01, 10, 100
7+
满足条件的子数组:每一位上 1 出现的次数为偶数次,异或结果为 0
8+
异或结果 <= 10^6,因此可以存储下 map[异或结果] = 前面的出现次数
9+
*/
10+
var beautifulSubarrays = function(nums) {
11+
let mp = {}, n = nums.length, xor = 0, ans = 0
12+
mp[0] = 1
13+
for (let i = 0; i < n; i++) {
14+
xor ^= nums[i]
15+
ans += mp[xor] ?? 0
16+
mp[xor] ??= 0
17+
mp[xor]++
18+
}
19+
return ans
20+
};

0 commit comments

Comments
 (0)