leetcode-题8-3sum

#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;
    vector<int>path;
    for (int i = 0; i < nums.size()-2; ++i)
    {
        int tem = tar - nums[i];
        int le = i + 1;
        int re = nums.size() - 1;
        while (le < re)
        {
            if (nums[le] + nums[re] == tem) {
                path.push_back(nums[i]);
                path.push_back(nums[le]);
                path.push_back(nums[re]);
                break;
            }
            if (nums[le] + nums[re] > tem)
                re--;
            if(nums[le] + nums[re] < tem)
                le++;
        }
    }
    int cnt = 1;
    for (auto i : path)
    {
        cout << i << ' ';
        if (cnt % 3 == 0)cout << endl;
        cnt++;
    }
        
    system("pause");
    return 0;
}

 

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