在C ++中的算术级数中找到缺少的数字
假设我们有一个按顺序表示算术级数元素的数组。缺少一个要素。我们必须找到缺失的元素。因此,如果arr=[2、4、8、10、12、14],则输出为6,因为缺少6。
使用二进制搜索,我们可以解决这个问题。我们将转到Middle元素,然后检查Middle和Next中间的区别是否与diff相同。如果不是,则在索引mid和mid+1之间存在丢失的元素。如果中间元素是AP中的第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