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 class Solution {
 2 public:
 3     int threeSumClosest(vector<int>& nums, int target) {
 4         sort(nums.begin(),nums.end());
 5 
 6         int ret;
 7         bool first=true;
 8 
 9         for(int i=0;i<nums.size();i++)
10         {
11             int j=i+1;
12             int k=nums.size()-1;
13 
14             while(j<k)
15             {
16                 int sum=nums[i]+nums[j]+nums[k];
17 
18                 if(first)
19                 {
20                     ret=sum;
21                     first=false;
22                 }else
23                 {
24                     if(abs(sum-target)<abs(ret-target))
25                         ret=sum;
26                 }
27 
28                 if(ret==target)
29                     return ret;
30 
31                 if(sum>target)
32                     k--;
33                 else
34                     j++;
35             }
36         }
37 
38         return ret;
39     }
40 };

 

posted on 2015-05-20 16:54  黄瓜小肥皂  阅读(218)  评论(0编辑  收藏  举报