在本指南中,我们将解释在 c++ 中查找所有可能的信息来查找具有奇数和的子数组的数量。为了找到奇数和的子数组的数量,我们可以使用不同的方法,所以这里是一个简单的例子 -
input : array = {9,8,7,6,5}output : 9explanation :sum of subarray -{9} = 9{7} = 7{5} = 5{9,8} = 17{8,7} = 15{7,6} = 13{6,5} = 11{8,7,6} = 21{9,8,7,6,5} = 35
暴力方法通过这种方法,我们可以简单地检查所有子数组中元素的总和是偶数还是奇数,如果是偶数,我们将拒绝该子数组并计算总和为奇数的子数组,这不是一种有效的方法,因为此代码的复杂度为 o(n2)。
示例#include <bits/stdc++.h>using namespace std;int main(){ int n=5, temp = 0; int a[n-1] = { 9,8,7,6,5 } ; // declaring our array. int cnt = 0; // counter variable. for(int i = 0; i < n; i++){ temp = 0; // refreshing our temp sum. for(int j = i; j < n; j++){ // this loop will make our subarrays starting from i till n-1. temp = temp + a[j]; if( temp % 2 == 1 ) cnt++; } } cout << "number of subarrays with odd sum : " << cnt << "\n"; return 0;}
输出number of subarrays with odd sum : 9
上述代码说明此代码中使用了嵌套循环,其中外层循环用于递增 i 的值,i 指向数组从头开始的每个值;内循环用于查找从位置 i 开始的具有奇数和的子数组。
高效方法在这种方法中,我们正在处理每个从数组中第 0 个位置开始的元素。如果当前元素是奇数,则为每个偶数增加一个奇数计数器并增加一个偶数计数器。如果我们找到一个奇数,则交换 even 和 odd 的值,因为向子数组添加奇数会改变其奇偶校验,最后向结果添加一个计数。这段代码的复杂度是 o(n),因为我们正在处理每个元素。
示例 #include <bits/stdc++.h>using namespace std;int main(){ int odd = 0, even = 0, result = 0,n=5,i,temp; int arr[ n-1 ] = { 9,8,7,6,5}; // initialising the array // for loop for processing every element of array for ( i = 0 ; i < n ; i ++ ) { if ( arr[ i ] % 2 == 0 ) { even++; } else { // swapping even odd values temp = even; even = odd; odd = temp + 1; } result += odd; } cout << "number of subarrays with odd sum : " << result;}
输出number of subarrays with odd sum : 9
上述代码的解释在这段代码中,我们检查每个元素的偶数/奇数,并为偶数增加偶数计数器,为奇数增加奇数计数器。此外,如果找到奇数,我们将交换奇偶计数器值;否则,它将改变子数组的奇偶校验。然后在每次迭代后将奇数计数器的值添加到结果变量中。
结论在本文中,我们解释了如何从 brute 中查找总和为奇数的子数组的数量强制方法,生成每个子数组的总和为奇数并递增计数。这段代码的时间复杂度是o(n2)。一种有效的方法是遍历数组的每个元素,并用找到的每个奇数/偶数增加奇数/偶数计数器变量,如果找到奇数则交换计数器;这段代码的时间复杂度是o(n)。希望您发现本文有助于理解问题和解决方案。
以上就是使用c++编写代码,找到具有奇数和的子数组的数量的详细内容。
