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

class Solution {
public:
int threeSumClosest(vector<int> &num, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int size = num.size();
if (size < 3)
{
return 0;
}
sort(num.begin(), num.end());   // 对于以下的处理过程必须事先排序，类似二分搜索
int result = 0;     // 记录最终结果
int distance = INT_MAX;    // signed int
int sum = 0;        // 中间结果
int i = 0, j , k ;

for(i = 0; i < size - 2; i++)    // 三元组的第一个元素一次遍历，范围为[0...n-3]
{
// 去重避免重复计算，如果和上次同则跳过
if (i > 0 && num[i] == num[i-1])
{
continue;
}

j = i + 1;  // 选定三元组第一个元素后，第二个元素从第一个元素的下一个位置开始考察
k = size - 1;   // 选定三元组第一个元素后，第三个元素从数组末尾开始考察
while (j < k)    // 三元组的后两个元素利用左右逼近来跳过效率，选定第一个元素后，其后的所有元素只需考察一遍
{
sum = num[i] + num[j] + num[k];
if (sum == target)  // 存在距离最近为0则直接返回，否则穷举选取非0最小距离
{
return sum;
}
else if(sum < target)
{
if((target - sum) < distance)
{
result = sum;
distance = target - sum;
}
j = j + 1;
// 避免重复计算，如果和上次同则跳过
if (num[j] == num[j-1])
{
j = j + 1;
}
}
else if(sum > target)
{
if((sum - target) < distance)
{
result = sum;
distance = sum - target;
}
k = k - 1;
// 避免重复计算如果和上次同则跳过
if (num[k] == num[k+1])
{
k = k -1;
}

}
}
}
return result;
}
};  

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

2014-10-30 16:57:05

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

2015-05-09 22:26:02

#### 3Sum Closest -- LeetCode

2014-02-22 23:22:01

#### 16. 3Sum Closest Leetcode Python

2015-01-17 10:10:08

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

2015-03-03 19:10:29

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

2016-06-07 21:47:12

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

2016-03-19 10:13:59

#### LeetCode-16-3Sum Closest(C语言实现)

2018-01-01 23:04:40

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

2016-04-29 21:18:52

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

2017-02-28 18:38:27

3Sum Closest