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


 1 int threeSumClosest(vector<int>& nums, int target) {
 2         int res,i;
 3         sort(nums.begin(),nums.end());
 4         int left,right,sum,dif=INT_MAX;
 5         int len=nums.size();
 6         for(i=0;i<len-1;i++)
 7         {
 8             left=i+1;right=len-1;
 9             while(left<right)
10             {
11                 sum=nums[i]+nums[left]+nums[right];
12                 if(sum==target)
13                 {
14                     return sum;
15                     
16                 }
17                 else if(sum<target)
18                 {
19                     if(target-sum<dif)
20                     {dif=target-sum;
21                     res=sum;}
22                     left++;
23                     
24                 }
25                 else
26                 {
27                     if(sum-target<dif)
28                     {
29                         dif=sum-target;
30                         res=sum;
31                     }
32                     right--;
33                 }
34             }
35         }
36         return res;
37     }