Leetcode15——三数之和为0

伴随着第二个数递增时,第三个数递减,所以采用双指针:

class Solution {
public:
    vector> threeSum(vector& nums) {
        int len=nums.size();
        sort(nums.begin(),nums.end());
        vector>result;
        for(int first=0;first0&&nums[first]==nums[first-1])
            {
                continue;
            }
            for(int second=first+1;secondfirst+1&&nums[second]==nums[second-1])
                {
                    continue;
                }
                 while(third>second&&nums[first]+nums[second]+nums[third]>0)
                 third--;
                if(third<=second)continue;
                if(nums[first]+nums[second]+nums[third]==0)
                {
                    result.push_back({nums[first],nums[second],nums[third]});
                    third--;
                }
            }
        }
        return result;
    }
};

 

你可能感兴趣的:(Leetcode)