LeetCode 15.3Sum

Given an array S of n integers, are there elements abc 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]
]

题目要求数组中所有满足和为0的三个元素的组合。因此可以考虑使用双指针算法,先对数组进行排序,然后从第一个数开始,对于第i个数,第i+1和最后一个数分别定为ab,由于数组为升序,因此,若第iab个数之和小于0,则a+1,若大于0,则b-1,若等于0,则说明这是所要求的其中一组元素。其中需要注意的是,题目要求结果的元素里面没有重复,因此当我们遇到连续的相同数字时要跳过。

class Solution {

public:

    vector<vector<int>> threeSum(vector<int>& nums) {

        vector<vector<int>> res;

        if(nums.size()<=2)

            return res;

        sort(nums.begin(),nums.end());

        for(int i=0;i<nums.size();i++){

            int a=i+1,b=nums.size()-1;

            while(a<b){

                if(nums[a]+nums[b]+nums[i]>0)

                    b--;

                else if(nums[a]+nums[b]+nums[i]<0)

                    a++;

                else{

                    vector<int> n(3,0);

                    n[0]=nums[i];

                    n[1]=nums[a];

                    n[2]=nums[b];

                    res.push_back(n);

                    while(a<b&&nums[b]==n[2])

                        b--;

                    while(a<b&&nums[a]==n[1])

                        a++;

                }

            }

            while(i<nums.size()-1&&nums[i+1]==nums[i])

                i++;

        }

        return res;

    }

};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值