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: 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>& nums) {
        int n = nums.size();

        if(n < 3)   return {};
        vector<vector<int>> res;

        sort(nums.begin(), nums.end());

        for(int i = 0; i < n; i++){
            //跳过重复的
            if(i > 0 && nums[i] == nums[i - 1])
                continue;

            int sum = -nums[i];

            int st = i + 1, en = n - 1;

            while(st < en){
                if(st < en && nums[st] + nums[en] == sum){
                    vector<int> temp;
                    temp.push_back(nums[i]);
                    temp.push_back(nums[st]);
                    temp.push_back(nums[en]);
                    res.push_back(temp);
                    st++;
                    //跳过与本次计算重复的
                    while(st < en && nums[st] == nums[st - 1])
                        st++;
                }else if(nums[st] + nums[en] < sum)
                    st++;
                else
                    en--;
            }
        }

        return res;
    }
};

results matching ""

    No results matching ""