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).
题目:三个相加,求离目标值最近的和。
可以用3sum的思路来,先固定一个数,剩余的头尾遍历,存最小值。但是这个思路超过时间限制,明天有空在研究下。
public static int threeSumCloest(int[] num , int target) {
if(num == null || num.length<3) return 0;
if(num.length == 3) return num[0] + num[1] + num[2];
Arrays.sort(num);
int min = Integer.MAX_VALUE;
int length = num.length;
int ret = 0;
for(int i = 0;i < length-2;i++){
int left = i+1;
int right = length-1;
if (i > 0 && num[i] == num[i-1]) continue;
while(left < right) {
int sum = num[i] + num[left] + num[right];
if(sum < target) {
if(target - sum < min) {
min = target - sum;
ret = sum;
}
left++;
} else if (sum > target) {
if(sum -target < min) {
min = sum - target;
ret = sum;
}
right--;
} else {
ret = sum;
}
}
}
return ret;
}