找到三数之和与target最接近,返回这三个数的和。假设答案唯一。
分析:与15.三数之和类似https://pigeon.blog.csdn.net/article/details/115711407,
同样采用 排序+双指针 方法。
public int threeSumClosest(int[] nums, int target) { int ans = nums[0]+nums[1]+nums[2]; int closest = Math.abs( ans - target); Arrays.sort(nums); int n = nums.length; //枚举a for (int first = 0; first < n; first++) { //twoSum int third = n-1; for (int second = first+1; second < n; second++) { while (second < third && (nums[first]+nums[second]+nums[third] - target)>0 ){ third--; } if (second == third) { if (second+1<n && Math.abs(nums[first]+nums[second]+nums[second+1]-target)<closest ) { ans = nums[first]+nums[second]+nums[second+1]; closest = Math.abs(ans-target); } } else { if (Math.abs(nums[first]+nums[second]+nums[third]-target)<closest) { ans = nums[first] + nums[second] + nums[third]; closest = Math.abs(ans-target); } if (third+1<n && Math.abs(nums[first]+nums[second]+nums[third+1]-target)<closest) { ans = nums[first] + nums[second] + nums[third+1]; closest = Math.abs(ans-target); } } } } return ans; }