假设我们有一个按顺序表示算术级数元素的数组。缺少一个要素。我们必须找到缺失的元素。因此,如果arr = [2、4、8、10、12、14],则输出为6,因为缺少6。
使用二进制搜索,我们可以解决这个问题。我们将转到居中元素,然后检查居中和居中的下一个之间的差异是否与diff相同。如果不是,则丢失元素出现在索引mid和mid +1之间。如果中间元素是AP中的第n / 2个元素,则丢失元素位于右半部分,否则位于左半部分。
#include <iostream> using namespace std; #define INT_MAX 999999 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 << "缺少的元素是: " << pg.missingElement(arr, n)<<endl; }
[2,4,8,10,12,14]
输出结果
缺少的元素是: 6