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).
https://oj.leetcode.com/problems/3sum-closest/
思路1:类似3Sum,区别是不需要去重,另外需要维护一个最小差值。
import java.util.Arrays;
public class Solution {
public int threeSumClosest(int[] num, int target) {
int n = num.length;
Arrays.sort(num);
int min = Integer.MAX_VALUE;
int result = 0;
for (int i = 0; i < n; i++) {
int start = i + 1, end = n - 1;
int sum = target - num[i];
int cur = 0;
while (start < end) {
cur = num[start] + num[end];
if (Math.abs(cur + num[i] - target) < min) {
min = Math.abs(cur + num[i] - target);
result = cur + num[i];
}
if (cur < sum)
start++;
else if (cur > sum)
end--;
else {
start++;
end--;
}
}
}
return result;
}
public static void main(String[] args) {
System.out.println(new Solution().threeSumClosest(new int[] { -1, 2, 1,
-4 }, 1));
System.out.println(new Solution().threeSumClosest(
new int[] { 1, 2, 3, }, 100));
}
}
来源:oschina
链接:https://my.oschina.net/u/1584603/blog/283673