LeetCode :3Sum

来源:互联网 发布:数据库完整性有哪些 编辑:程序博客网 时间:2024/06/06 12:36

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:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie,abc)
  • 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)
把之前的也写上来吧。

class Solution {public:    vector<vector<int> > threeSum(vector<int> &num) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        vector<vector<int> > res;        int n = num.size();        if(n ==0 )return res;        vector<int> tuple(3);        sort(num.begin(), num.end());        int val = num[0] - 1;        for(int i = 0 ;i < n - 2; ++i){            int j = i + 1;            int k = n-1;            if(num[i] == val)                continue;            val = num[i];            while(j < k ){                if(num[i] + num[j] + num[k] == 0){                    tuple[0] = num[i];                    tuple[1] = num[j];                    tuple[2] = num[k];                    res.push_back(tuple);                    while(num[++j] == num[j - 1] && j < k);                    while(num[--k] == num[k + 1] && j < k);                }                else if(num[i] + num[j] + num[k] > 0){                    --k;                }                else{                    ++j;                }            }        }        return res;    }};


原创粉丝点击