数组中奇数和的三联体计数
- 最后更新 : 2021年8月10日
给定一个有N个 整数的数组 arr[] ,求 i、j和 k的三倍数,使1<=i < j < k <= N且arr[i]+ arr**[j] + arr[k] 是奇数。**
例子。
**输入:**arr[] = {1, 2, 3, 4, 5}
**输出。**4
解释。 给定的数组包含4个总和为奇数的三联体。它们是{1, 2, 4}、{1, 3, 5}、{2, 3, 4}和{2, 4, 5}。**输入:**arr[] ={4, 5, 6, 4, 5, 10, 1, 7}
**输出。**28
**天真的方法。**给定的问题可以通过遍历数组中所有可能的无序三联体来解决,并跟踪三联体的数量,使其总和为奇数。
时间复杂度。 O(N3)
高效的方法。上述方法可以利用以下整数的属性进行优化。
- 奇数+偶数+偶数=奇数
- 奇数 + 奇数 + 奇数 = 奇数
因此,为了实现上述想法,我们可以计算数组中的偶数和奇数的数量。因此,安排一个奇数和两个偶数的不同方法是OC1 *EC2 -> (O * E * (E-1))/2,安排三个奇数的不同方法是OC3**->** (O * (O-1) * (O-2))最后的答案将是上述两个数值的总和。
下面是上述方法的实现。
C++
// C++ Program for the above approach#include <iostream>using namespace std;// Function to count the number of// unordered triplets such that their// sum is an odd integerint countTriplets(int arr[],int n){// Count the number of odd and// even integers in the arrayint odd = 0, even = 0;for (int i = 0; i < n; i++) {if (arr[i] & 1)odd++;elseeven++;}// Number of ways to create triplets// using one odd and two even integersint c1 = odd * (even * (even - 1)) / 2;// Number of ways to create triplets// using three odd integersint c2 = (odd * (odd - 1) * (odd - 2)) / 6;// Return answerreturn c1 + c2;}// Driver Codeint main(){int arr[] = { 4, 5, 6, 4, 5, 10, 1, 7 };int n =sizeof(arr) /sizeof(int);// Function Callint ans = countTriplets(arr, n);// Print Answercout << ans;return 0;} |
输出
28
时间复杂度。 O(N)
辅助空间。 O(1)
读者请注意!现在不要停止学习。以学生可接受的价格获得所有重要的DSA概念。 DSA自学课程以适合学生的价格掌握所有重要的DSA概念,并为行业做好准备。 要完成从学习语言到DS Algo以及更多的准备工作,请参考 完整的面试准备课程.
如果你想参加专家的现场课程 ,请参考 针对在职专业人士的DSA现场课程 和 面向学生的竞争性编程直播.
我的个人笔记 arrow_drop_up
保存