这题的思路和3Sum一样,只是要考虑一下k在j+1之后是不是需要减1,因为不是0而是绝对值最小,所以有点难考虑= = 我就懒得去想直接没-1 汗啊
public class Solution {
public int threeSumClosest(int[] num, int target) {
Arrays.sort(num);
int tempClose = Integer.MAX_VALUE;
int tempsum = Integer.MAX_VALUE;
for (int i = 0; i != num.length; ++i){
int k = num.length - 1;
for (int j = i + 1; j < k; j++){
while (num[i] + num[j] + num[k] - target > 0 && k > (j+1))
k--;
int close = Math.abs(num[i] + num[j] + num[k] - target);
if (close < tempClose){
tempClose = close;
tempsum = num[i] + num[j] + num[k];
}
if (k < num.length - 1){
close = Math.abs(num[i] + num[j] + num[k+1] - target);
if (close < tempClose){
tempClose = close;
tempsum = num[i] + num[j] + num[k+1];
}
k++;
}
}
}
return tempsum;
}
}