The combination of Ordered arrays

Source: Internet
Author: User

Question itself from: http://blog.csdn.net/koudaidai/article/details/8066395

The order of a series is better than that of M | M-N1 * N2 | the smallest N1 N2. These two numbers are in this series.

Basic Idea: A pointer from the beginning and end to move in the middle. for example, for header N1, tail N2, N1 * N2> m, it can be inferred that all values after N1 and N2 are larger than m, so N2 --

The source code is as follows:

Void getmostclose (INT array [], int a_len, int m)
{
Int pre_ I = 0, I = 0;
Int pre_j = a_len-1, j = a_len-1;

Int max_base = (1 <31)-1;
STD: cout <max_base <Endl;
While (j> I)
{
Int curr = array [I] * array [J];

Int diff = (m-curr );
If (diff <0) diff * =-1;
If (diff <max_base)
{
Pre_ I = I;
Pre_j = J;
Max_base = diff;
}

Else if (curr <= m)
I ++;
Else
J --;
}
STD: cout <"m =" <m <", I =" <array [pre_ I] <", j = "<array [pre_j] <Endl;
}

Int main ()

{

Int A [12] = {1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
Getmostclose (A, sizeof (a)/sizeof (INT), 49 );

}

Result output:

2147483647
M = 49, I = 4, j = 12

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.