3Sum leetcode

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:

  • 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)
我们可以在 2sum问题 的基础上来解决3sum问题,假设3sum问题的目标是target。每次从数组中选出一个数k,从剩下的数中求目标等于target-k的2sum问题。这里需要注意的是有个小的trick:当我们从数组中选出第i数时,我们只需要求数值中从第i+1个到最后一个范围内字数组的2sum问题。
我们以选第一个和第二个举例,假设数组为A[],总共有n个元素A1,A2....An。很显然,
当选出A1时,我们在子数组[A2~An]中求目标位target-A1的2sum问题,我们要证明的是当选出A2时,我们只需要在子数组[A3~An]中计算目标位target-A2的2sum问题,而不是在子数组[A1,A3~An]中,证明如下:
假设在子数组[A1,A3~An]目标位target-A2的2sum问题中,存在A1 + m = target-A2(m为A3~An中的某个数),即A2 + m = target-A1,这刚好是“对于子数组[A3~An],目标位target-A1的2sum问题”的一个解。即我们相当于对满足3sum的三个数A1+A2+m = target重复计算了。因此为了避免重复计算,在子数组[A1,A3~An]中,可以把A1去掉,再来计算目标是target-A2的2sum问题。

对于本题要求的求最接近解,只需要保存当前解以及当前解和目标的距离,如果新的解更接近,则更新解。算法复杂度为O(n^2);
注意:我们这里是求的和是一个非确定性的数,因此
2sum问题的hashtable解法就不适合这里了
 为了避免重复,对于排序后的数组,当我们枚举第一个数时,如果遇到重复的就直接跳过;当我们找到一个符合的二元组(第二个数和第三个数)时,也分别对第二个数和第三个数去重。

class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
        vector<vector<int> > res;
        if(num.size()<3)
        return res;
        sort(num.begin(),num.end());
        for(int i = 0;i<num.size()-2;i++) {
            if(i>0 && num[i] == num[i-1])
            continue;
            int target = 0 - num[i];
            sumTwo(num,target,i+1,res);
        }
        return res;
    }
    void sumTwo(vector<int>& num,int target,int start,vector<vector<int> >& res) {
        vector<int> tmp;
        int end = num.size()-1;
        int front = start;
        while(start<end) {
            tmp.clear();
            if((num[start]+num[end]) == target) {
                if(start>front && num[start] == num[start-1]) { //重复,跳过
                    ;
                } else {
                    tmp.push_back(num[front-1]);
                    tmp.push_back(num[start]);
                    tmp.push_back(num[end]);
                    res.push_back(tmp);
                }
                    start++;
                    end--;
            } else if((num[start]+num[end]) > target) {
                end--;
            } else {
                start++;
            }
        }
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值