【问题】
题目描述
输入一个递增排序的数组和一个数字S,在数组中查找两个数,是的他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的。
输出描述:
对应每个测试案例,输出两个数,小的先输出。
【解决】
① 还是双指针
import java.util.ArrayList;
public class Solution {
public static void main(String[] args){
int[] array = {1,2,3,4,5,6,7,8};
ArrayList<Integer> res = FindNumbersWithSum(array,5);
for (int i = 0;i < res.size();i ++){
System.out.print(res.get(i) + " ");
}
}
public static ArrayList<Integer> FindNumbersWithSum(int [] array,int sum) {
ArrayList<Integer> res = new ArrayList<>();
if (array == null || array.length < 2){
return res;
}
int start = 0;
int end = array.length - 1;
boolean hasRes = false;
while(start < end){
if (array[start] + array[end] == sum){
if (! hasRes){
res.add(array[start]);
res.add(array[end]);
hasRes = true;
}else {
int multi1 = array[start] * array[end];
int multi2 = res.get(0) * res.get(1);
if (multi1 < multi2){
res.set(0,array[start]);
res.set(1,array[end]);
}
}
start ++;
end --;
}else if (array[start] + array[end] < sum){
start ++;
}else {
end --;
}
}
return res;
}
}