3Sum Closest

Question:

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.

Solution:

 1 class Solution {
 2 public:
 3     int threeSumClosest(vector<int>& nums, int target) {int result=0;
 4     if(nums.size()<3)
 5         return result;
 6     sort(nums.begin(),nums.end());
 7     int gap=abs(nums[0]+nums[1]+nums[2]-target);
 8     auto last=nums.end();
 9     for(auto i=nums.begin();i<last-2;i++)
10     {
11         auto j=i+1;
12         auto k=last-1;
13         while(j<k)
14         {
15             if(abs(*i+*j+*k-target)<=gap)
16             {
17                 result=*i+*j+*k;
18                 gap=abs(*i+*j+*k-target);
19             }
20             if((*i+*j+*k)<target)
21                 j++;
22             else k--;
23         }
24     }
25     return result;
26         
27     }
28 };

posted on 2015-07-08 22:00  Riden  阅读(151)  评论(0编辑  收藏  举报

导航