3 Sum

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)

分析:

这道题原本不难,但是题目要求结果不能够包含重复的 triplets, 往往容易出错。

思路1:

step 1: 先排序

step 2:   枚举前两个数,如果要满足 sum = 0, 那么第三个数必须是 前两个数和的负数。

              通过二分搜索去查找。。复杂度 是 O(N^2 * lgN)


思路2:

O(N^2)的算法。

借助于 2 sum的思路:如果在一个已经排序的数组中,寻找两个数的和为给定的sum, 其实有 O(N)的算法。

指针 i, j  分别指向数组的首尾,如果 num[i] + num[j] < 0, 则 i++;  如果 > 0, j--; 直到和等于sum.

因此,本题可以 

step 1:   排序

step 2:  先枚举第一个数,然后在排好序的数组中寻找 两个数和等于 第一个数的负数。

Note: 为了避免重复的 triplets, 有一些小细节需要考虑。具体见下面的代码。

          基本的思想就是 如果碰到相邻的数相同,可以跳过。


class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
        vector<vector<int> > result;
        if(num.size() < 3) return result;
        
        sort(num.begin(), num.end());
        
        //处理以num[k]开头的和
        for(int k=0; k<num.size()-2; ++k){
            if(k > 0 && num[k] == num[k-1]) continue; //避免重复
            
            int i=k+1, j=num.size()-1; //分别指向首尾
            while(i < j){
                if(i > k+1 && num[i] == num[i-1]){
                    ++i;
                    continue;
                }
                if(j < num.size()-1 && num[j] == num[j+1]){
                    --j;
                    continue;
                }
                    
                if(num[k] + num[i] + num[j] < 0)
                    ++i;
                else if(num[k] + num[i] + num[j] > 0) 
                    --j;
                else{
                    result.push_back(vector<int>{num[k], num[i++], num[j--]});
                }
            }
        }
        
        return result;
    }
};


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值