leetcode-题7--3Sum Closest

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
    int a[6] = { -1,0,1,2,-1,-4 };
    vector<int>nums(a, a + 6);
    sort(nums.begin(), nums.end());
    int tar;
    cin >> tar;
    int res = 0;
    int min_abs = 10000;
    for (auto i = nums.begin(); i < nums.end() - 2; ++i)
    {
        auto b = next(i);
        auto c = prev(nums.end());
        while (b < c)
        {
            const int sum = *i + *b + *c;
            const int gab = abs(sum - tar);
            if (min_abs > gab)
            {
                res = sum;
                min_abs = gab;
            }
            if (sum > tar) c--;
            else b++;
        }
    }
    cout << res;
    system("pause");
    return 0;
}

 

posted @ 2017-05-23 17:29  babyking1  阅读(99)  评论(0编辑  收藏  举报