C ++ searches for the first two numbers that appear in the sorted array and the value (requires the time complexity to be o (n ).
# Include <iostream> using namespace std; // enter an array and a number that have been sorted in ascending order. // search for two numbers in the array, so that the sum of them is exactly the number entered. // The time complexity is O (n ). If there are multiple pairs of numbers and the sum is equal to the input number, output any one. // For example, input array 1, 2, 4, 7, 11, 15, and number 15. Because 4 + 11 = 15, 4 and 11 are output. Void Grial (int a [], int x, int y) {int j = X-1; int I = 0; while (a [j]> y) {j --;} while (I <j) {while (a [I] + a [j])> y) j --; if (a [I] + a [j])> y) {j --;} else if (a [I] + a [j]) <y) {I ++ ;} else {cout <a [I] <endl; cout <a [j] <endl; return ;}}} // note that the time complexity is o (n) at most. Find it from both sides. I don't know whether this algorithm is available or there is a better algorithm, but when I encountered this problem, I thought about it. // I am very happy to solve it. I hope to cheer up with you. int main () {int a [] = {1, 2, 3, 4, 5, 6, 7, 8, 9,100,300 0}; Grial (a, 11,3003 ); return 0 ;}