16. 3Sum Closest(C++)

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

Solution 

class Solution {
public:
  int threeSumClosest(vector<int>& nums, int target) {
    if(nums.size()<3) return 0;
    int number=nums[0]+nums[1]+nums[2];
    std::sort(nums.begin(),nums.end());
    for(int i1=0;i1<nums.size();i1++){
      if(i1>0 && nums[i1]==nums[i1-1]) continue;
      int i2=i1+1;
      int i3=nums.size()-1;
      while(i2<i3){
        int sum=nums[i1]+nums[i2]+nums[i3];
        if(sum==target) return sum;
        if(abs(target-number)>abs(target-sum)) number=sum;
        if(sum>target){
          i3--;
        }else{
          i2++;
        }
      }
    }
    return number;
  }
};


posted @ 2017-03-05 19:21  DevinGu  阅读(169)  评论(0编辑  收藏  举报