C++中从给定数组中查找缺失的偶数和奇数元素
问题陈述
给定两个整数数组 even[] 和 odd[],它们分别包含连续的偶数和奇数元素,每个数组都缺少一个元素。任务是找到缺失的元素。
示例
If even[] = {10, 8, 6, 16, 12} and odd[] = {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 到 minEven 的偶数和,记为 sum1,以及从 2 到 maxEven 的偶数和,记为 sum2。
- even 数组所需的和将为 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 = 14 Missing odd number = 5
广告