leetcode -- 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)

分析:
(i)首先将序列从小到大排序,然后找出第一个非负数的位置nonnegPos,分成负数和非负数子序列
(ii)一个负数+两个非负数 -- 首先确定一个负数a,然后在非负数子序列中寻找2个数,其和为-a
(iii)一个非负数+两个负数 -- 同理调用twoSum()
(iii)三个零

bool isNonnegative(int i) {  return (i >= 0); }
class Solution {
public:
    void twoSum(vector<vector<int> > &ret, vector<int>::iterator beg, vector<int>::iterator end, int num)
    {
        vector<int> triplet(1, -num);
        vector<int>::iterator e = end - 1;
        for(vector<int>::iterator b = beg; b < end; b++)
        {
            if(b > beg && *b == *(b - 1))  continue;
            while(b < e){
                if(*b + *e== num){
                    triplet.push_back(*b);  triplet.push_back(*e);  sort(triplet.begin(), triplet.end());
                    ret.push_back(triplet);  triplet.assign(1, -num);
                    break;
                }
                else if( e != end - 1 && *b + *e < num){ e++; break; }
                e--;
            }
        }
    }
    vector<vector<int> > threeSum(vector<int> &num) {
        vector<int>::iterator beg = num.begin(), end = num.end(); 
        vector<vector<int> > ret; vector<int>::size_type ix;
        sort(beg, end);
        vector<int>::iterator nonnegPos = find_if(beg, end, isNonnegative);     
        for(ix = 0; ix < nonnegPos - beg; ix++){
            if(ix > 0 && num[ix] == num[ix - 1]) continue;
            twoSum(ret, nonnegPos, end, -num[ix]);
        }
         for(ix = nonnegPos - beg; ix < num.size(); ix++){
            if(ix > nonnegPos - beg && num[ix] == num[ix - 1]) continue;
            twoSum(ret, beg, nonnegPos, -num[ix]);
        }
        if(count(beg, end, 0) >= 3){
            vector<int> zero(3, 0);
            ret.push_back(zero);
        }
       return ret;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值