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).
public class Solution {
public int threeSumClosest(int[] nums, int target) {
int len = nums.length;
if(len<3)return 0;
Arrays.sort(nums);
int res = nums[0]+nums[1]+nums[2];
for(int i = 0;i<len-2;i++){
int left = i+1;
int right = len-1;
while(left<right){
int sum = nums[i]+nums[left]+nums[right];
if(sum==target)return target;
res = Math.abs(sum-target)>Math.abs(res-target)?res:sum;
if(sum<target)left++;
else right--;
}
}
return res;
}
}
time=23ms;
三个数及以上的,在找的时候,要定下一个,动另外两个,不能三个全动。。。