Subject address:
https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/
Given a length nnArray of n AAA , ask the number of non-empty sub-arrays whose sum is odd. The result modulo1 0 9 + 7 10^9+7109+Return after 7 .
First find the prefix and the array c [i] c[i]c[i]即 c [ i ] = ∑ k = 0 i − 1 A [ k ] c[i]=\sum_{k=0}^{i-1}A[k] c[i]=∑k=0i−1A [ k ] , and then use a hash table to record the number of even and odd prefix sums. Then traverseAAA , TohokuA [i] A [i]When A [ i ] , if the prefix andc [i + 1] c[i+1]c[i+1 ] is an odd number, then look upc [0: i] c[0:i]c[0:How many even numbers are there in i ] , add them up, and getA [i] A[i]A [ i ] is the number of sub-arrays whose sum of the right end point is an odd number; if the prefix andc [i + 1] c[i+1]c[i+1 ] is an even number and similarly. code show as below:
public class Solution {
public int numOfSubarrays(int[] arr) {
int MOD = (int) (1E9 + 7);
// 为了加速,可以用数组代替哈希表,count[0]代表偶数个数,[1]代表奇数个数;
// 空数组的前缀和是0,要计入
int[] count = {
1, 0};
int res = 0;
// 为了节省空间,不需要另外开数组算前缀和,可以直接用一个变量记录
for (int i = 0, rem = 0; i < arr.length; i++) {
rem = (rem + arr[i]) % 2;
res = (res + count[rem ^ 1]) % MOD;
count[rem]++;
}
return res;
}
}
Time complexity O (n) O(n)O ( n ) , spaceO (1) O (1)O ( 1 )。