Leetcode 3Sum

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)
题目的意思是:给出一个整型数组,找出所有三个元素的组合,其组合之和等于0。要求在结果中不含重复组合
可以先将数组排序,从头依次挑选出第一个元素,在其后选两个元素。这样将3Sum转换成2Sum了。
充分利用有序的属性,使用分别在首尾的两指针来挑选两个元素。
注意重复组合的过滤
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(num[i] > 0) break;      //第一个数如果大于0,则后面的数肯定大于0
            if(i > 0 && num[i] == num[i-1]) continue; //去除重复的元素
            int start = i+1, end = num.size()-1;
            while(start < end){
                int sum = num[start]+num[end]+num[i];
                if(sum < 0) start++;
                else if(sum > 0 ) end--;
                else {
                    vector<int> a;
                    a.push_back(num[i]);
                    a.push_back(num[start]);
                    a.push_back(num[end]);
                    res.push_back(a);
                    //忽略可能相同的结果
                    do{start++;}while(start<end && num[start] == num[start-1]);
                    do{end--;}while(start<end && num[end] == num[end+1]);
                }
            }
        }
        return res;
    }
};


 
原文地址:https://www.cnblogs.com/xiongqiangcs/p/3823920.html