100 question _ 10 search for the two numbers for the given value in the sorting Array

Source: Internet
Author: User
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 ;
}

 

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.