在C ++中缺少给定数组中的偶数和奇数元素
问题陈述
给定两个整数数组even []和奇数[],它们分别包含连续的偶数和奇数元素,每个数组中都缺少一个元素。任务是找到缺少的元素。
示例
If even[] = {10, 8, 6, 16, 12} andodd[] = {3, 9, 13, 7, 11} then
missing number from even array is 14 and from odd array is 5.
算法
将even []数组中的最小和最大偶数元素存储在变量minEven和maxEven中
前N个偶数之和为N *(N +1)。计算从2到min的偶数之和甚至说sum1和从2到max的偶数之和
偶数数组的所需总和为reqSum = sum2 – sum1 + minEven,从此reqSum中减去even []数组总和将得出缺失的偶数
同样,也可以找到丢失的奇数,因为我们知道前N个奇数的总和为N2
示例
#include <bits/stdc++.h>using namespace std;
void findMissingNums(int even[], int sizeEven, int odd[], int sizeOdd) {
int minEven = INT_MAX;
int maxEven = INT_MIN;
int minOdd = INT_MAX;
int maxOdd = INT_MIN;
int sumEvenArr = 0, sumOddArr = 0;
for (int i = 0; i < sizeEven; i++) {
minEven = min(minEven, even[i]);
maxEven = max(maxEven, even[i]);
sumEvenArr += even[i];
}
for (int i = 0; i < sizeOdd; i++) {
minOdd = min(minOdd, odd[i]);
maxOdd = max(maxOdd, odd[i]);
sumOddArr += odd[i];
}
int totalTerms = 0, reqSum = 0;
totalTerms = minEven / 2;
int evenSumMin = totalTerms * (totalTerms + 1);
totalTerms = maxEven / 2;
int evenSumMax = totalTerms * (totalTerms + 1);
reqSum = evenSumMax - evenSumMin + minEven;
cout << "Missing even number = " << reqSum - sumEvenArr << "\n";
totalTerms = (minOdd / 2) + 1;
int oddSumMin = totalTerms * totalTerms;
totalTerms = (maxOdd / 2) + 1;
int oddSumMax = totalTerms * totalTerms;
reqSum = oddSumMax - oddSumMin + minOdd;
cout << "Missing odd number = " << reqSum - sumOddArr << "\n";
}
int main() {
int even[] = {10, 8, 6, 16, 12};
int sizeEven = sizeof(even) / sizeof(even[0]);
int odd[] = {3, 9, 13, 7, 11};
int sizeOdd = sizeof(odd) / sizeof(odd[0]);
findMissingNums(even, sizeEven, odd, sizeOdd);
return 0;
}
当您编译并执行上述程序时。它产生以下输出-
输出结果
Missing even number = 14Missing odd number = 5
以上是 在C ++中缺少给定数组中的偶数和奇数元素 的全部内容, 来源链接: utcz.com/z/338100.html