3 sum

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.

题目要求:

  • 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.

每个三元组内的元素是按非递减的顺序存放的,并且结果中要求不含有相同的集合。

解法:首先是排序,接着要求是不含有相同的集合,显然可以使用set,但是下面的代码全部都避免使用set


下面一共使用了3种方法:

法一:DFS,复杂度高,并且在很小的例子上都超时。

class Solution {
private:
    void helper(const vector &A, int cur_index, const int max_index, int cur_sum , vector &cur_set, set > & ret)
    {
        if(cur_sum > 0 ) return;
        if(cur_index > max_index)
        {
            if(cur_set.size() == 3 && cur_sum == 0 )
            {
                ret.insert(cur_set);
            }
            return;
        }
        cur_set.push_back(A[cur_index]);
        helper(A,cur_index+1, max_index, cur_sum+A[cur_index],cur_set,ret);
        cur_set.pop_back();
        helper(A,cur_index+1,max_index,cur_sum,cur_set,ret);
        return;
    }
public:
    vector > threeSum(vector &num)
    {
        vector > ret;
        if(num.empty()) return ret;
    
        sort(num.begin(), num.end());
    
        int max_index = num.size()-1;
    
        vector cur;
        set > ret2;
    
        helper(num, 0, max_index, 0, cur, ret2);
    
        for(auto a:ret2)
        {
            ret.push_back(a);
        }
        return ret;
    }
};

法二:枚举所有的2-sum和。再在数组中查找是否存在另外一个数,使得该3个数的和为0.

此法不需要使用set,直接就可以得到结果,但是要注意避免重复计算,如下两点。


注1:上述的枚举2-sum时,对于剩下的那个数只需要在 “下标都大于前两者时”进行。如下例:


在上图中,当枚举到i和j时,另外一个元素只需要在  图示的 k  范围内枚举即可。

注2:如果数组中有大量的重复元素,那么i和j(保持有A[i] == A[j])就只需要考虑一次即可。

如下例:


上图中,i 和 j只需要考虑一次, 当 j 移动到 j‘ 的时候,是不需要考虑的,因为与前面的 i 和 j  是重复的。

代码如下:

class Solution {
private:
//二分查找另一个数字
int findAnother(const vector &A, int left, int right, int target)
{
    if(A.empty()) return -1;
    //int left=0,right=A.size()-1;
    while(left <= right)
    {
        int mid=left+(right-left)/2;
        if(A[mid] == target) return mid;
        if(A[mid] < target) left = mid+1;
        else right=mid-1;
    }
    return -1;
}
public:
    vector > threeSum(vector &num)
    {
        vector > ret;
        if(num.empty()) return ret;
        
        int n = num.size();
        vector temp(3,0);
        
        sort(num.begin(), num.end()); //首先排序
        
        for(int i=0;i 0 && num[i]==num[i-1]) //避免重复计算,导致输出集合中的重复的元素
                continue; 
                
            if(num[i] > 0) break;  //由于数组值有序的,当前的num[i]如果大于0,可直接break,因为后面的不可能满足了
            
            for(int j=i+1;j i+1 && num[j]==num[j-1]) //避免重复计算,导致输出集合中的重复的元素
                    continue;
                    
                int sum2 = num[i]+num[j];
                if(sum2 > 0) break;  //由于数组值有序的,当前的和如果大于0,可直接break
                
                int index = findAnother(num,j+1,n-1,0-sum2);
                if(index != -1)
                {
                    temp[0] = num[i]; temp[1]=num[j]; temp[2]=num[index];
                    ret.push_back(temp);
                }
            }
        }
        return ret;
    }
};

时间复杂度为: n^2(logn)

法三:由于2-sum在数组有序的情况下我们是可以O(n)的时间来解决的,于是直接使用已有的2-sum的代码,代码如下:
class Solution {
public:
    vector > threeSum(vector &num)
    {
        vector > ret;
        if(num.empty()) return ret;
        
        int n = num.size();
        vector temp(3,0);
        
        sort(num.begin(), num.end());
        
        for(int i = 0 ; i < n-2; ++i)
        {
            if(i > 0 && num[i] == num[i-1])
                continue;
                
            int left = i+1, right = n-1;
            int target = -num[i];
            
            while(left < right)
            {
                if(left > i+1 && num[left] == num[left-1])  //避免重复加入
                {
                    left++;
                    continue;
                }
                if(right < n-1 && num[right] == num[right+1])  //避免重复加入
                {
                    right--;
                    continue;
                }
                
                int sum = num[left] + num[right];
                if(sum ==  target)
                {
                    temp[0] = num[i]; 
                    temp[1]=num[left],
                    temp[2]= num[right];
                    ret.push_back(temp);
                    left++;
                    right--;
                }
                else if(sum > target) right--;
                else left++;
            }
            
        }
        return ret;
    }
};



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值