15. 3Sum

来源:互联网 发布:哪个软件直播笑傲江湖 编辑:程序博客网 时间:2024/04/30 13:50

Title

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note: The solution set must not contain duplicate triplets.

For example, given array S = [-1, 0, 1, 2, -1, -4],A solution set is:[  [-1, 0, 1],  [-1, -1, 2]]

Solution

目前刷题,都用C++

2Sum问题的进一步3Sum,将其变为2Sum。

class Solution {public:    vector<vector<int>> threeSum(vector<int>& nums) {        vector<vector<int>> vb;        if(nums.size() < 3) {            return vb;        }        sort(nums.begin(), nums.end());        //几个小问题(却让略头疼...):        // 1.a和a的下一位置元素值相同,跳过;        // 2.b/c和b/c的下/前一位置元素相同,跳过;        // 3.b和c相同,没问题。        for(decltype(nums.size()) i=0; i!=(nums.size()-2); ++i) {            if(i != 0 && nums[i] == nums[i-1]){                continue;            }            auto a = nums[i];            auto b = nums.begin()+i+1;            auto c = nums.end()-1;            while(b != c) {                if((*b+*c) == (-a)) {                    vector<int> v;                    v.push_back(a); //空vector,不可用下标去访问任何元素。                    v.push_back(*b); //不可v[1] = *b;                    v.push_back(*c);                    // if(!(find(vb.begin(), vb.end(), v) != vb.end())) {//v not in vb                    //     vb.push_back(v);                    // } //超时                    vb.push_back(v);                    ++b;                    while(*b == *(b-1) && b!=c) { //跳过                        ++b;                    }                }                else if((*b+*c) < (-a)) {                    ++b;                    while(*b == *(b-1) && b!=c) {                        ++b;                    }                }                else {                    --c;                    while(*c == *(c+1) && b!=c) {                        --c;                    }                }            }        }        return vb;    }};

runtime: 64ms

之后再还有3Sum的变种等,以后再整。

0 0
原创粉丝点击