Microsoft and other data structures and algorithms interview 100 questions 14th questions

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.