题目:
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).
public class TribleSumClosest {
public static int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int res = nums[0] + nums[1] + nums[nums.length - 1];
for (int i = 0; i < nums.length - 2; i++) {
int start = i + 1;
int end = nums.length - 1;
while (start < end) {
int sum = nums[start] + nums[end] + nums[i];
if (sum > target) {
end--;
}
else {
start++;
}
if (Math.abs(target - sum) < Math.abs(target - res)) {
res = sum;
}
}
}
return res;
}
public static void main(String[] args) {
int[] nums = {-1, 2, 1, -4};
int target = 1;
System.out.println(threeSumClosest(nums, target));
}
}
本文介绍了一个寻找数组中三个整数,使其和最接近给定目标值的算法实现。通过排序和双指针技巧,有效地解决了这个问题,并提供了一个具体的示例代码,展示了如何在给定数组[-1,2,1,-4]和目标值1的情况下找到最接近的三数之和。
179

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



