Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
思路:同上篇博客,稍加变化而已。
import java.util.Arrays;
public class Solution {
public int threeSumClosest(int[] nums, int target) {
if (nums.length < 3) {
return 0;
}
Arrays.sort(nums);
int value = nums[0] + nums[1] + nums[2];
for (int i = 0; i < nums.length; i++) {
if (i >= 1 && nums[i] == nums[i - 1]) {
continue;
}
int j = i + 1;
int k = nums.length - 1;
while (j < k) {
int nowValue = nums[i] + nums[j] + nums[k];
if (Math.abs(nowValue - target) < Math.abs(value - target)) {
value = nowValue;
}
if (nowValue > target) {
while (k > j && k <= nums.length - 2 && nums[k] == nums[k - 1]) {
k--;
}
k--;
} else if (nowValue < target) {
while (j < k && j >= 1 && nums[j] == nums[j + 1]) {
j++;
}
j++;
} else {
return target;
}
}
}
return value;
}
}

本文介绍了一个算法问题的解决方案,即在给定整数数组中找到三个数,使得这三个数的和最接近给定的目标值。通过排序和双指针技巧实现了高效的求解方法。
719

被折叠的 条评论
为什么被折叠?



