14th questions
Question: enter an array and a number that have been sorted in ascending order,
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.
Analysis:
This question is relatively simple. See the code. Note: The code is all the combinations provided.
Code:
[Cpp]
# Include <iostream>
Using namespace std;
Bool findSum (int * a, const int length, int sum)
{
Bool yesno = false;
Int startIndex = 0;
Int endIndex = length-1;
If (endIndex <1) return false;
Int tempSum;
While (startIndex <endIndex)
{
TempSum = a [startIndex] + a [endIndex];
If (tempSum> sum)
{
EndIndex --;
}
Else if (tempSum <sum)
{
StartIndex ++;
}
Else
{
Cout <a [startIndex] <"" <a [endIndex] <endl;
Yesno = true;
StartIndex ++;
}
}
Return yesno;
}
Int main ()
{
Int a [10] = {1, 2, 4, 5, 6, 7, 8, 9, 10 };
Cout <findSum (a, 10, 10 );
Return 0;
}
The output result is
1 9
2 8
3 7
4 6