15 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]
]

Solution

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> res;
        int n = nums.size();
        if ( n <= 2 ) return res;
        sort(nums.begin(), nums.end());
        for ( int i = 0; i <= n-3; i++ ) {
            if ( i >= 1 and nums[i] == nums[i-1] ) continue;
            int j = i+1, k = n-1;
            while ( j <= k-1 ) {
                if ( j >= i+2 and nums[j] == nums[j-1] ) { j += 1; continue;}
                if ( k <= n-2 and nums[k] == nums[k+1] ) { k -= 1; continue;}
                int sum = nums[j] + nums[k] + nums[i];
                if ( sum == 0 ) {
                    int tmp[] = {nums[i], nums[j], nums[k]};
                    vector<int> tmpV(tmp, tmp+3);
                    res.push_back(tmpV);
                    k -= 1;
                    j += 1;
                }
                if ( sum > 0 ) k -= 1;
                if ( sum < 0 ) j += 1;
            }
        }
        return res;
    }
};

Notes

  • Be careful with duplicates, consider the following case:
    [-4, -1, -1, 0, 0, 1, 1, 1, 2, 2]
    
    One has to take care of duplicates for all three pointers.
    When nums[i] == nums[i_last], skip it!
  • Note the way to construct vectors with an array:
    int tmp[] = {nums[i], nums[j], nums[k]};
    vector<int> tmpV(tmp, tmp+3);
    

results matching ""

    No results matching ""