/*
1 遍历整个数组
2 起始点和结束点 从前后往中间遍历
3 比较和与target的差值 小的存入结果当中
注意 ans 初始值不能付最大 ;
*/
class Solution {
public int threeSumClosest(int[] nums, int target) {
if(nums == null || nums.length < 3) return -1;
Arrays.sort(nums);
int ans = nums[0] + nums[1] + nums[2];
for(int i = 0; i < nums.length - 2; i++) {
int start = i + 1;
int end = nums.length - 1;
while(start < end) {
int sum = nums[i] + nums[start] + nums[end];
if(Math.abs(sum - target) < Math.abs(ans - target)) {
ans = sum;
}
if(sum > target) {
end--;
} else if (sum < target) {
start++;
} else {
return target;
}
}
}
return ans;
}
}