# [LeetCode][Java] 3Sum Closest

## 题目：

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

## 题意：

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

## 算法分析：

参考博客：http://www.zhuangjingyang.com/leetcode-3sum/

## AC代码：

<span style="font-size:12px;">public class Solution
{
private  int minVal = Integer.MAX_VALUE;
private  int result = 0;
public  int threeSumClosest(int[] num, int target)
{
Arrays.sort(num);
//if number is less than 3 or num is null it's can't be calc
if(num.length <3 ||  num ==null)
return target;
for(int i=0;i<num.length;i++)
{
if(i>0 && num[i] == num[i-1])
continue;
find(i,num,num[i],target);
}
return result;
}
public  void find(int index,int[] num,int target,int res)
{
int l = index+1; //low is equal to index+1 just because we just search element that is bigger than itself
int r = num.length - 1;
while(l<r)
{
if( Math.abs(num[l] + num[r] + target - res) <= minVal)
{
minVal = Math.abs(num[l] + num[r] + target - res);//it's more closer
result = num[l] + num[r] + target;
}
if(num[l] + num[r] + target >res)
r--;
else
l++;
}
}
}</span>

• 本文已收录于以下专栏：

## LeetCode 16 3Sum Closest(C,C++,Java,Python)

Problem: Given an array S of n integers, find three integers in S such that the sum is closest ...
• runningtortoises
• 2015年05月09日 22:26
• 1729

## 【LeetCode】3Sum Closest 解题报告

【题目】 Given an array S of n integers, find three integers in S such that the sum is closest to a gi...
• ljiabin
• 2014年10月30日 16:57
• 7787

## leetcode-java-16. 3Sum Closest

• github_34514750
• 2016年06月07日 21:47
• 487

## 16. 3Sum Closest Leetcode Python

Given an array S of n integers, find three integers in S such that the sum is closest to a given num...
• hyperbolechi
• 2015年01月17日 10:10
• 695

## leetcode第16题——**3Sum Closest

• buptlrw
• 2016年01月22日 14:58
• 360

## LeetCode16——3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given num...
• booirror
• 2015年03月12日 00:00
• 1308

## [LeetCode] 016. 3Sum Closest (Medium) (C++/Java/Python)

[LeetCode] 016. 3Sum Closest (Medium) (C++/Java/Python)
• hcbbt
• 2015年03月03日 19:10
• 2502

## [LeetCode]3Sum

• zhouworld16
• 2013年11月24日 11:20
• 7435

## 【LeetCode】3Sum 解题报告

• ljiabin
• 2014年10月30日 16:00
• 28597

## LeetCode 15 3Sum (C,C++,Java,Python)

Problem: Given an array S of n integers, are there elements a, b, c in S such that a + b + c = ...
• runningtortoises
• 2015年05月09日 21:06
• 4061

举报原因： 您举报文章：[LeetCode][Java] 3Sum Closest 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)