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