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).
题意:
给定一个数组和一个值target,找出其中3个元素,使其加起来最接近target。
Solution1:Two Pointers(left and right to meet each other)
1. Sort the array (coz we must check the duplicates)
2. Lock one pointer and do two sum with the other two
3. Keep updating the gap between given target with result. The smaller gap is, the closer result is.
code
/*
Time Complexity: O(n^2). For each locked item, we need traverse the rest of array behind such item.
Space Complexity: O(1). We only used constant extra space.
*/
class Solution {
public int threeSumClosest(int[] nums, int target) {
int result = 0;
int minGap = Integer.MAX_VALUE;
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
int j = i + 1;
int k = nums.length - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
int gap = Math.abs(target - sum);
// keep updating the gap. The smaller gap is, the closer result is.
if (gap < minGap) {
result = sum;
minGap = gap;
}
// two pointers(left and right to meet each other)
if (sum < target) {
j++;
} else {
k--;
}
}
}
return result;
}
}