##题目描述
输入一个递增排序的数组和一个数字S,在数组中查找两个数,是的他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
解题思路
指针对撞法,采用双指针法,i,j从数组两端开始往中间靠拢,
如果 array[i]+array[j] < sum 则j++,如果array[i]+array[j]>sum 则 i–, 如果array[i]+array[j]==sum 那么 i++,j– 同时更新最小值。
程序实现
public class Solution {
public ArrayList<Integer> FindNumbersWithSum(
int []
array,
int sum) {
ArrayList<Integer> res=
new ArrayList<Integer>();
if(
array==null)
return res;
int i=
0,j=
array.length-
1;
int min=Integer.MAX_VALUE;
while(i<j){
int temp1=
array[i]+
array[j];
if(temp1==sum){
int temp2=
array[i]*
array[j];
if(temp2<min){
res.clear();
res.add(
array[i]);
res.add(
array[j]);
min=temp2;
}
i++;
j--;
}
else if(temp1<sum){
i++;
}
else{
j--;
}
}
return res;
}
}