问题
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
想法
三个数的和仍然是转化为两个输的和,先固定一个数。
Code
class Solution {
public int threeSumClosest(int[] num, int target) {
Arrays.sort( num );
int sum = 0;
if( num.length <= 3){
for( int i = 0 ; i<num.length ;i++){
sum += num[i];
}
return sum;
}
int ans;
ans = num[0] + num[1] + num[2];
//固定一个数
for ( int i = 0 ;i< num.length -2;i++){
int lo = i + 1 ;
int hg = num.length - 1 ;
//二分策略
while( lo < hg ){
sum = num[i] + num[lo] + num[hg];
if(Math.abs(sum - target) < Math.abs(ans-target)){
ans = sum;
if( ans == target )
return target;
}
//比较的是sum和target的差距
if ( sum < target )
lo++;
else
hg--;
}
}
return ans;
}
}
问题
- 不要总想着这个问题很简单,有简单的方法,很多时候看似简单的问题,解决时就是很麻烦,不要觉得自己的想法就很麻烦
- 仔细读题,看题目出题的边界,三个数的和,既然没有规定数组的长度,那么首要考虑的就是数组的长度,不足三个数时,直接相加就是最接近的结果
- 初试化定义一个离target差距最远的结果,然后迭代不断缩小这个结果