3Sum

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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, abc)
  • 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)

注:
先排序。
a+b+c=0;
-c=a+b;
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
          vector<vector<int> >ans;
        sort(nums.begin(),nums.end());//algorithm中
        for(int i=0;i<nums.size();i++){
            if(i>0&&nums[i]==nums[i-1])
                continue;
            int target=-nums[i];
            int start=i+1,end=nums.size()-1;
            while(start<end){
                if(start>i+1&&nums[start-1]==nums[start]){
                    start++;
                    continue;
                }
                if(nums[start]+nums[end]<target)
                    start++;
                else if(nums[start]+nums[end]>target)
                    end--;
                else{
                    vector<int> triple;
                    triple.push_back(nums[i]);
                    triple.push_back(nums[start]);
                    triple.push_back(nums[end]);
                    ans.push_back(triple);//二维vector的元素为vector<int>,所以push(vector<int>)
                    start++;
                }
            }    
        }
        return ans;
    }
};

 

以上是关于3Sum的主要内容,如果未能解决你的问题,请参考以下文章