问题描述
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).
问题分析
这道题只让我们返回结果,所以直接三重循环暴力求解。
代码实现
public int threeSumClosest(int[] num, int target) {
int sum, error, result, min = Integer.MAX_VALUE;
sum = error = result = 0;
for (int i = 0; i < num.length; i++) {
for (int j = i + 1; j < num.length; j++) {
for (int k = j + 1; k < num.length; k++) {
sum = num[i] + num[j] + num[k];
error = Math.abs(target - sum);
if (error < min) {
min = error;
result = sum;
}
}
}
}
return result;
}
网友评论