LeetCode15:3Sum

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)
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

class solution{
public:
        void insertsort(vector<int>&a,int n)
        {
            int temp;
            for(int i = 1;i <n;i++)
            {
                temp = a[i];
                int j;
                for(j = i;j>0&& temp<a[j-1] ;--j)
                {
                    a[j] = a[j-1];
                }
                a[j] = temp;
            }
        }

        vector< vector<int>> threeSum(vector<int>&num){
        vector<vector<int>> res;

        if (num.size() < 3)
            return res;
        //对原数组进行非递减(递增)排序
        InsertSort(num, num.size());

        for (int i = 0; i < num.size(); ++i)
        {
            //去重
            if (i != 0 && num[i] == num[i - 1])
                continue;
            //如果num[i] = num[i - 1],说明刚才i-1时求的解在这次肯定也会求出一样的,所以直接跳过不求

            int p = i + 1, q = num.size() - 1;
            int sum = 0;

            //夹逼法寻找第2,第3个数
            while (p < q)
            {
                sum = num[i] + num[p] + num[q];
                if (sum == 0)
                {
                    vector<int> newRes;
                    newRes.push_back(num[i]);
                    newRes.push_back(num[p]);
                    newRes.push_back(num[q]);
                    insertsort(newRes, newRes.size());
                    res.push_back(newRes);

                    //寻找其他可能的两个数,顺带去重
                    //这个去重操作主要针对有多个同值的数组,如: {- 3, 1, 1, 1, 2, 2, 3, 4}
                    //当sum == 0,我们保存了当前解以后,需要num[i]在解中的其他的2个数组合,这个时候,肯定是p往后或者q往前,如果++p,发
                //现其实num[p] == num[p - 1],说明这个解肯定和刚才重复了,再继续++p。同理,如果--q后发现num[q] == num[q + 1],继续--q。
                    while (++p < q && num[p - 1] == num[q])
                    {
                        //do nothing
                    }
                    while (--q > p && num[q + 1] == num[q])
                    {
                        //do nothing
                    }
                }
                else if (sum < 0) //sum太小,p向后移动
                {
                    ++p;
                }
                else                    //sum太大,q向前移动
                {
                    --q;
                }

            }
        }

        return res;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值