标签:
[Problem]
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).
[Analysis]
思路跟3Sum没有区别,只是输出变成了跟由集合内3个数字组合成与target差距最小的数。
[Solution]
import java.util.Arrays; public class Solution { public int threeSumClosest(int[] num, int target) { int min = num[0] + num[1] + num[2]; Arrays.sort(num); for (int i = 0; i < num.length - 2; i++) { if (i > 0 && num[i] == num[i - 1]) { continue; // if current value is already tested as the first element, skip; } // Do 2Sum int head = i + 1; int tail = num.length - 1; while (head < tail) { if (head > i + 1 && num[head] == num[head - 1]) { head++; continue; // if current value is already tested as the second, skip; } if (tail < num.length - 1 && num[tail] == num[tail + 1]) { tail--; continue; // similar test for the third element } int sum = num[i] + num[head] + num[tail]; if (sum == target) { return sum; } else if (sum > target) { tail--; } else { head++; } if (Math.abs(sum - target) < Math.abs(min - target)) { min = sum; } } } return min; } }
标签:
原文地址:http://www.cnblogs.com/zhangqieyi/p/4865445.html