码迷,mamicode.com
首页 > 编程语言 > 详细

16. 3Sum Closest(C++)

时间:2017-03-05 20:35:29      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:ret   3sum   sum   public   --   put   number   vector   array   

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;
  }
};

16. 3Sum Closest(C++)

标签:ret   3sum   sum   public   --   put   number   vector   array   

原文地址:http://www.cnblogs.com/devin-guwz/p/6506372.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!