leetcode---3Sum

来源:互联网 发布:狂发短信软件 编辑:程序博客网 时间:2024/06/06 07:16

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, a ≤ b ≤ c)
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>> ans;    vector<vector<int>> threeSum(vector<int>& nums)     {        if(nums.size() < 3)            return ans;        sort(nums.begin(), nums.end());        int n = nums.size();        for(int i=0; i<n-2; i++)        {            if(i>0 && nums[i] == nums[i-1])                continue;            int l = i + 1;            int r = n - 1;            while(l < r)            {                int s = nums[i] + nums[l] + nums[r];                if(s == 0)                {                    vector<int> tmp;                    tmp.push_back(nums[i]);                    tmp.push_back(nums[l]);                    tmp.push_back(nums[r]);                    ans.push_back(tmp);                    while(l<r && nums[l] == nums[l+1])                        l++;                    while(l<r && nums[r] == nums[r-1])                        r--;                    l++;                    r--;                }                else if(s < 0)                    l++;                else                    r--;            }        }        return ans;    }};
0 0
原创粉丝点击