Title description
Input an ascending array and a number S. Find two numbers in the array so that their sum is exactly S. If the sum of multiple pairs of numbers is equal to S, output the smallest product of the two numbers.
Enter
[1,2,4,7,11,15],15
Return value
[4,11]
answer
Use double pointers. Initialize the pointers i,j
at the head and end of the array respectively. When arr[i]+arr[j]<sum
it means that the two numbers are too small, you want to i++
get a larger number, on the contrary, you must j--
get a smaller number. If arr[i]+arr[j]=sum
, then it is the desired result. When comparing whether the product of this result is smaller, if it is smaller, update the result
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> FindNumbersWithSum(int[] array, int sum) {
int len = array.length, multi;
ArrayList<Integer> res = new ArrayList<>();
if (len == 0) return res;
multi = array[len - 1] * array[len - 1];
int i = 0, j = len - 1, res1 = 0, res2 = 0;
while (i < j) {
if (array[i] + array[j] > sum)
j--;
else if (array[i] + array[j] < sum)
i++;
else {
if (multi > array[i] * array[j]) {
multi = array[i] * array[j];
res1 = array[i];
res2 = array[j];
}
i++;
}
}
if (multi != array[len - 1] * array[len - 1]) {
res.add(res1);
res.add(res2);
System.out.println(res1 + " " + res2);
}
return res;
}
}