*Leetcode - 3Sum Closest

来源:互联网 发布:mysql的级联删除 编辑:程序博客网 时间:2024/05/20 08:43
public class Solution {
    public int threeSumClosest(int[] num, int target) {
       if (num.length < 3)
return 0;

Arrays.sort(num);
int min = num[0] + num[1] + num[num.length - 1], sum, d;
for (int i = 0; i < num.length - 2; i++) {
int m = i + 1, j = num.length - 1;
if(i>0 && num[i] == num[i-1])
  continue;

while (m < j) {
sum = num[i] + num[m] + num[j];
if (Math.abs(sum - target) < Math.abs(min - target)) {
min = sum;
if (sum == target)
return min;
}

if (sum > target)
j--;
else
m++;
}
}
return min;
    }

}

-------------------------------------------

HINT: 

确定其中一个,剩下的两个靠近; 记录每一次的和,随时替换。

=========================

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).

0 0