(**leetcode_Array) 3Sum

3Sum

  Total Accepted: 48690  Total Submissions: 288511 My Submissions
Question  Solution 

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)

Show Tags
  Array Two Pointers
Have you met this question in a real interview? 
Yes
 
No

Discuss

其实就是两个sum相加targe的变化,用一个i固定即可

class Solution {
    vector > ret;
public:
    vector > threeSum(vector &num) {
        if(num.size()<3)
            return ret;
        sort(num.begin(),num.end());
        for(int i=0; i0&&num[i]==num[i-1]) //注意去重
                continue;
            judge(num, i, i+1, num.size()-1);
        }
        return ret;
    }
    void judge(vector &num, int i, int left, int right){
        
        while(left0)
                right--;
            else if((num[i]+num[left]+num[right])<0)
                    left++;
                 else{
                     vector ans;
                     ans.push_back(num[i]);
                     ans.push_back(num[left]);
                     ans.push_back(num[right]);
                     ret.push_back(ans);
                     left++;
                     right--;
                     while(left//注意去重
                        left++;
                     while(left//注意去重
                        right--;
                 }
        }
    }
};


你可能感兴趣的:(刷题找工作)