3Sum

作者: lc_fan | 来源:发表于2019-07-08 10:21 被阅读0次

Given an array nums of n integers, are there elements a, b, c in nums 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.

Example:
Given array nums = [-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>& nums) {
        vector<vector<int>> result; 
        sort(nums.begin(), nums.end());
        int n = nums.size();
        for(int i =0;i<n;i++){
            if(i== 0 || (i!=0 && nums.at(i) != nums.at(i-1)) ){
                int a = nums.at(i);
                int l = i+1;
                int r = n-1;
                int target = -a;
                while(l<r){
                    int sum = nums.at(l) + nums.at(r);
                    if(sum == target){
                        result.push_back({a,nums.at(l),nums.at(r)});
                        while(l < r && nums.at(l) == nums.at(l+1))
                            l++;
                        while(l < r && nums.at(r) == nums.at(r-1))
                            r--;
                        l++;r--;
                    }else if(sum > target){
                        r--;
                    }else{
                        l++;
                    }
                }
            }
        }
        return result;
    }
};

相关文章

网友评论

      本文标题:3Sum

      本文链接:https://www.haomeiwen.com/subject/ehwnhctx.html