/**
* 给定一个整数数组和一个目标值,找出数组中和最接近目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 12, 15], target = 13
因为 nums[0] + nums[2] = 2 + 12 = 14 最接近目标值
所以返回 [0, 2]
**/
解题思路:最为接近和相等不太一样,最为接近需要匹配所有可能值后才能得出结论
相当于找到绝对值最小的两个值的索引,就最里层循环就转化为了最小绝对值的筛选
private static int[] closesetSumTwo(int [] arrs,int target){
int closesetDiffIndex1=0;
int closesetDiffIndex2=0;
int closesetDiffResult = Math.abs(target - arrs[0]);
for (int i = 0; i < arrs.length; i++) {
int tmp = target - arrs[i];
for (int j = i +1; j < arrs.length; j++) {
if(closesetDiffResult > Math.abs(tmp - arrs[j])){
closesetDiffResult =Math.abs(tmp - arrs[j]);
closesetDiffIndex1= i;
closesetDiffIndex2= j;
}
}
}
return new int[]{closesetDiffIndex1,closesetDiffIndex2};
}
扩展为一个数组找出,最接近目标的三个数的位置(结果唯一)
思路:相当于外层多一成循环
private static int[] closesetSumThree(int [] arrs,int target){
int closesetDiffIndex1=0;
int closesetDiffIndex2=0;
int closesetDiffIndex3=0;
Integer closesetDiffResult = null;
for (int m = 0; m < arrs.length; m++) {
int tmpTarget = Math.abs(target - arrs[m]);
for (int i = m + 1; i < arrs.length; i++) {
int tmp = Math.abs(tmpTarget - arrs[i]);
for (int j = i + 1; j < arrs.length; j++) {
if(closesetDiffResult != null && closesetDiffResult < Math.abs(tmp - arrs[j])){
continue;
}
closesetDiffResult = Math.abs(tmp - arrs[j]);
closesetDiffIndex1 = m;
closesetDiffIndex2 = i;
closesetDiffIndex3 = j;
}
}
}
return new int[]{closesetDiffIndex1,closesetDiffIndex2,closesetDiffIndex3};
}
思考:如果层级大2的话 可以先排序然后再进行折半查找 这样时间复杂度会优化不少。如果要求结果是最接近n个数之和的位置呢?(在嵌套循环不太现实 虽然理论上可实现,后面会尝试一下递归方式)