用 C++ 找出等差数列中的缺失数
假设我们有一个数组,按顺序表示等差数列的元素。缺少一个元素。我们必须找到缺失的元素。所以,如果 arr = [2, 4, 8, 10, 12, 14],输出为 6,因为缺少 6。
使用二分查找,我们可以解决这个问题。我们将转到中间元素,然后检查中间和中间相邻元素之间的差是否与 diff 相同。如果不是,则缺失的元素存在于索引 mid 和 mid + 1 之间。如果中间元素是等差数列中的第 n/2 个元素,那么缺失元素位于右半部分,否则位于左半部分。
示例
#include <iostream> using namespace std; class Progression { public: int missingUtil(int arr[], int left, int right, int diff) { if (right <= left) return INT_MAX; int mid = left + (right - left) / 2; if (arr[mid + 1] - arr[mid] != diff) return (arr[mid] + diff); if (mid > 0 && arr[mid] - arr[mid - 1] != diff) return (arr[mid - 1] + diff); if (arr[mid] == arr[0] + mid * diff) return missingUtil(arr, mid + 1, right, diff); return missingUtil(arr, left, mid - 1, diff); } int missingElement(int arr[], int n) { int diff = (arr[n - 1] - arr[0]) / n; return missingUtil(arr, 0, n - 1, diff); } }; int main() { Progression pg; int arr[] = {2, 4, 8, 10, 12, 14}; int n = sizeof(arr) / sizeof(arr[0]); cout << "The missing element is: " << pg.missingElement(arr, n); }
输出
The missing element is: 6
广告