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).
分析:
從一個(gè)整形數(shù)組中找出三個(gè)數(shù)字之和最接近目標(biāo)值。
和上一個(gè)題類似,遍歷數(shù)組,找到與目標(biāo)值距離最小的三個(gè)數(shù)之和涉波。時(shí)間復(fù)雜度O(n^2)刷晋。
Java:
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int res = nums[0] + nums[1] + nums[2];
for (int i = 0; i < nums.length - 2; i++) {
int lo = i + 1, hi = nums.length - 1;
while (lo < hi) {
int sum = nums[i] + nums[lo] + nums[hi];
if (sum > target) {
hi--;
} else {
lo++;
}
if (Math.abs(sum - target) < Math.abs(res - target)) {
res = sum;
}
}
}
return res;
}