Query the specified character functions in the array

Source: Internet
Author: User

Query the specified character functions in the array

# Include <iostream>

Using namespace std;

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 (a, 5, 15, x, y ))
Cout <x <"" <y <endl;
Return 0;
}

We can find the first number and the last number of the array. When the sum of two numbers is greater than the input number,

Move a large number forward. When the sum of the two numbers is smaller than the number, move the smaller number backward.

When they are equal, end the job. In this way, the scanning order is from the two ends of the array to the middle of the array.

Related Article

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.