3Sum Closest

来源:互联网 发布:基金产品概括 知乎 编辑:程序博客网 时间:2024/05/28 23:11

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

#include <iostream>#include <vector>#include <algorithm>#include <cstdlib>#include <climits>using namespace std;class Solution{public:    int threeSumCloset(vector<int> &num, int target)    {        int result= 0, min_closet=INT_MAX;        sort(num.begin(),num.end());        for (auto i=num.begin(); i != num.end(); ++i)        {            auto j = i + 1;            auto k = num.end() - 1;            while (j < k)            {                int sum = *i + *j + *k;                int difference = abs(target-sum);                if (difference < min_closet)                {                    min_closet = difference;                    result = sum;                }                if (target < sum)                    --k;                else                    ++j;            }        }        return result;    }};int main(){    vector<int> num={-1,2,1,-4};    int result = 0;    Solution solution;    result = solution.threeSumCloset(num,1);    cout<<result<<endl;    return 0;}

这里写图片描述

0 0