Question: enter an array and a number that have been sorted in ascending order, and search for two numbers in the array so that their sum 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 arrays 1, 2, 4, 7, 11, 15, and numbers 15. Because 4 + 11 = 15, 4 and 11 are output.
If you think about it, you will find that you can directly greedy the sorted array. First we find the first number and the last number of the array. When the sum of two numbers is greater than the input number, move the larger number forward. When the sum of the two numbers is smaller than the number, move the smaller number backward. When the two numbers are equal, close the job. In this way, the scanning order is from the two ends of the array to the middle of the array. This can be proved by Reverse verification.
CodeAs follows:
Code # Include < Iostream >
Using NamespaceSTD;
Bool Find ( Int A [], Int N, Const Int & Sum, Int & X, Int & Y)
{
Int I = 0 , J = N - 1 , Csum;
While (I < J)
{
Csum = A [I] + A [J];
If (Csum = Sum)
{
X = A [I];
Y = A [J];
Return True ;
}
Else If (Csum < Sum)
I ++ ;
Else
J -- ;
}
Return False ;
}
Int Main ()
{
Int A [] = { 1 , 4 , 7 , 11 , 15 };
Int X, Y;
If (Find (, 5 , 15 , X, y ))
Cout < X < " " < Y < Endl;
Return 0 ;
}