Address https://www.acwing.com/solution/leetcode/content/5801/
Title Description
give you an integer array nums and an integer k.
If there is exactly one k odd sub-array digital, we think this is a sub-array "Yumiko array."
Please return this number array "Yumiko array" of.
Example 1 : Input: the nums = [ 1 , 1 , 2 , 1 , 1 ], K = . 3 Output: 2 Explanation: contains . 3 th sub-array of an odd number is [ 1 , 1 , 2 , 1 ] and [ 1 , 2 , 1 , 1 ]. Example 2 : Input: the nums = [ 2 , . 4 , . 6 ], K = . 1 Output: 0 explanation: the number of columns does not contain any odd number, the array does not exist Yumiko. Example 3: Input: the nums = [ 2 , 2 , 2 , . 1 , 2 , 2 , . 1 , 2 , 2 , 2 ], K = 2 Output: 16 Tip: . 1 <= nums.length <= 50000 . 1 <the nums = [I ] <= 10 ^ . 5 . 1 <= K <= nums.length
1 algorithm
violence enumeration is not to say the TLE
For example,
nums = [2,2,2,1,2,2,1,2,2,2], k = 2
violence enumeration is certainly
2 2 1 2 2 1 2
2 2 2 2 2 1 1 2
2 2 . 1 2 2 2 2 2. 1
2. 1 2 2 2 2 2 2 2. 1
2 2 1 2 2 1
2 2 1 2 2 1 2
2 2 1 2 2 1 2 2
2 2 1 2 2 1 2 2 2
A total of 16 groups .....
Observe the law
to facilitate consideration of the sliding window
I first calculate the beginning of the end is in line with an odd array of odd K
can then fill in the calculation of both sides even-number
final answer - the number of sub-arrays, in fact, is the number of programs that can be selected on the left multiplied by the number of programs you can choose the right
That is the basic array 1,2,2,1 extended to the left.
Multiplying the left to the right filling can be filled even even
(left can be filled with three 2, 3 can be filled with the right 2, together with the end of the beginning of the odd array can be considered a basic choice)
so that the final result is (3+ 1) * (1 + 3) = 16
Code
class Solution { public: int numberOfSubarrays(vector<int>& nums, int k) { if (nums.size() < k) return 0; int ret = 0; vector<int> v; for (int i = 0; i < nums.size(); i++) { if (nums[i] % 2 != 0) v.push_back(i); } //得到所有为奇数的下标索引 vector<pair<int, int >> VP; int I = 0 ; the while (I + K <= v.size ()) { int A = V [ 0 + I]; int B = V [K + I - . 1 ]; vp.push_back ( a {, B}); I ++ ; } // for each K is just right subarray and odd odd at the beginning of the end and then calculated for ( int I = 0 ; I <vp.size (); I ++ ) { int A = VP [I] .first; int B = VP [I] .second; // calculate how many left can add in the even IF (I == 0 ) A = A + . 1 ; the else { A = A - VP [I - . 1 ] .first; } // calculate the number of the right may be added to the even come IF (I vp.size == () - . 1 ) B = nums.size () - B; the else { B = VP [I + . 1 ] .second - B; } RET + = A * B; } return RET; } };