3Sum

Posted IIcyZhao

tags:

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

class Solution 
public:
    vector<vector<int> > threeSum(vector<int> &num) 
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<int> > result;
        set<vector<int> > record;
        if (num.size() < 3) 
            return result;
        
        sort(num.begin(), num.end());
        vector<int> got;
        int sum = 0;
        for (int i = 0; i < num.size() - 2; ++i) 
            int low = i + 1;
            int high = num.size() - 1;
            while (low < high) 
                sum = num[i] + num[low] + num[high];
                if (sum == 0) 
                    got.push_back(num[i]);
                    got.push_back(num[low]);
                    got.push_back(num[high]);
                    if (record.find(got) == record.end()) 
                        record.insert(got);
                        result.push_back(got);
                    
                    got.clear();
                    --high;
                 else if (sum > 0) 
                    --high;
                 else 
                    ++low;
                
            
        
        return result;
    
;


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

[Leetcode] 3Sum

3Sum

15. 3Sum

3sum

3Sum Closest

15. 3Sum