Leetcode 3Sum Closest

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).
给一个整型数组,找出三个数使其和尽可能的接近给定的数,返回三个数的和
注意题目有个假设对于每个输入都有一个解决方法,与3Sum差不多
class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        sort(num.begin(),num.end());
        int closet = num[0]+num[1]+num[2];
        for(int i = 0 ; i < num.size()-2; ++ i){
            int start = i+1, end = num.size()-1,sum = 0;
            while(start <  end){
                sum = num[i] + num[start] + num[end];
                if(sum == target) return sum;
                else if(sum > target) end--;
                else start++;
                closet = abs(sum - target) < abs(closet-target) ? sum : closet;
            }
        }
        return closet;
    }
};


 
原文地址:https://www.cnblogs.com/xiongqiangcs/p/3823984.html