# 16. 3Sum Closest

class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int n=nums.size();
int i,j,k;
int ans=nums[0]+nums[1]+nums[2];
sort(nums.begin(),nums.end());

for(i=0;i<=n-3;i++)
{
if(i>0&&nums[i]==nums[i-1])
continue;
for(j=i+1,k=n-1;j<k;)
{
if(j>i+1&&nums[j]==nums[j-1])
{
j++;
continue;
}
if(k<n-1&&nums[k]==nums[k+1])
{
k--;
continue;
}
int d=nums[i]+nums[j]+nums[k];
if(d==target)
return d;
else if(d>target)
k--;
else
j++;
if(abs(d-target)<abs(ans-target))
ans=d;
}
}
return ans;
}
};

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

2015-05-09 22:26:02

#### Leetcode #16 3Sum Closest 找3数之和最接近 解题小节

2016-03-19 10:13:59

#### leetcode-java-16. 3Sum Closest

2016-06-07 21:47:12

#### 16. 3Sum Closest Leetcode Python

2015-01-17 10:10:08

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

2014-10-30 16:57:05

#### 15. 3Sum，16. 3Sum Closest，18. 4Sum（最后一个方法重要）重要

2017-02-28 18:38:27

#### 15. 3Sum/16. 3Sum Closest(C++)

2017-06-30 11:06:59

#### 【LeetCode】LeetCode——第16题：3Sum Closest

2016-04-29 21:18:52

#### 3Sum Closest -- LeetCode

2014-02-22 23:22:01

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

2015-03-03 19:10:29