16. 3Sum Closest
Tags: ‘Array’, ‘Two Pointers’
Given an array nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Solution
类似 15 3Sum, 先排序再左右夹逼。 O(n2) O(1)
public int threeSumClosest(int[] nums, int target) {
if (nums == null || nums.length == 0) return 0;
if (nums.length <= 3) return Arrays.stream(nums).sum();
Arrays.sort(nums);
int minGap = Integer.MAX_VALUE;
int result = 0;
for (int i = 0; i < nums.length - 1; i++) {
if (i > 0 && nums[i] == nums[i-1]) continue;
int lo = i + 1, hi = nums.length - 1;
while (lo < hi) {
int sum = nums[i] + nums[lo] + nums[hi];
int gap = Math.abs(target - sum);
if (gap < minGap) {
minGap = gap;
result = sum;
}
if (sum == target) {
break;
} else if (sum < target) {
lo++;
} else {
hi--;
}
}
}
return result;
}