思路:这个题用数学方法还是挺容易想通,左右指针l,r分别指向符合count==k的子数组的两个奇数端点,统计l左边的偶数(包括l)和r右边的偶数(包括r),那么res+=二者的乘积;然后将l++,r++,对下一个符合条件的子数组进行同样的操作,大致思想就是这样;
int numberOfSubarrays(vector<int> &nums, int k)
{
int len = nums.size();
int l = 0, r = 1;
int count = 0, count_left = 0, count_right = 0;
int res = 0;
bool flag = true;
while (true)
{
//首先找到两个首尾端奇数,分别用l,r指向
while (!(nums[l] & 1) && l < len)
{
l++;
count_left++;
}
count_left++; //包括这个奇数
if (l == len)
{
return res;
}
else
{
l++; //l指向奇数后一个数
if (flag)
{
r = l;
count = 1;
}
while (r < len && count < k)
{
if (nums[r] & 1)
{
count++;
}
r++;
}
if (r == len)
{
if (count == k)
res += count_left;
return res;
}
else //现在是count==k 并且nums[r]为奇数
{
count_right = 1;
while (!(nums[r] & 1) && r < len)
{
r++;
count_right++;
}
//此时r指向奇数后的一个数 或者 结尾
res += count_right * count_left;
if (r == len)
return res;
else
{
count--;
count_right = 0;
count_left = 0;
flag = false;
}
}
}
}
return res;
}