3Sum

Jin Shang bio photo By Jin Shang

Given an array nums of n integers, are there elements a, b, c in numssuch 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

Solution:

Loop through i and do a standard 2 sum. Use while loops to skip duplicate values

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int> > ans;
        sort(nums.begin(),nums.end());

        for(int i=0;i<nums.size();i++){
            int a = i+1;
            int b = nums.size()-1;
            while(a<b){
                int target = -nums[i];
                int x = nums[a], y=nums[b];
                if(x+y>target) b--;
                else if(x+y<target)a++;
                else{
                    ans.push_back(vector<int>{nums[i],x,y});
                    while(a+1<nums.size()&&nums[a+1]==x) a++;
                    while(b-1>i&&nums[b-1]==y)b--;
                    a++;b--;
                }
            }
            while(i+1<nums.size()&&nums[i+1]==nums[i])i++;
        }
        return ans;
    }
};