Class Findclosestpairexample {public static void Findandprintclosest (int[] arrayone, int expectedsum) {int Le NOne = Arrayone.length; The array length, which is all filled by default. int diff = Integer.max_value; Defines the difference between the two number and the expected value; The default takes the largest integer int resultone = 0;//the first element int resulttwo = 0;//another element int leftindex = 0;//to the left of the array subscript int rightindex = lenOne-1; Right-start array subscript while (Leftindex < lenone && rightindex >= 0 && leftindex! = Rightindex) {//If left subscript Do not exceed the length of the array, the right subscript is not less than 0, and the left and the same elements are unequal if (Math.Abs (Arrayone[leftindex] + Arrayone[rightindex]//If the difference between two numbers and minus the expected value is smaller than the current difference, Description found a more appropriate element combination-Expectedsum) < diff) {resultone = arrayone[leftindex];//Update result value Resulttwo = Arrayone[rightindex]; diff = Math.Abs (resultone + resulttwo-expectedsum);//Update difference} else if (Arrayone[leftindex] + Arrayone[rightinde X] < Expectedsum) {//If the current difference is still minimal and the sum of two is smaller than the expected value, it should increase the left leftindex++; } else {//If the current difference is still minimal and the sum of two is greater than the expected value, it should be reduced to the right rightindex--; }//if}//end of While System.out.printf ("[%d,%d] \ n", Resultone, Resulttwo); } public static void Main (string[] args) {int[] Arrayone = {-5,-1, 0, 1, 4, 5, 7, 9};//ordered array System.ou T.println ("Two of the minimum difference from expected 20 is:"); Findandprintclosest (Arrayone, 20); }}
Program Run Result:
Given an integer sum, look for an element, B, from an array of n ordered elements, so that the result of A+b is closest to sum