Two pointer solution C++......O(n^2)


#1
vector<vector<int>> Solution::threeSum(vector<int> &A) {
    vector<vector<int>> ans;
    if(A.empty()) return ans;
    sort(A.begin(), A.end());
    for(int i=0; i<A.size()-1; i++){
        if(i>0 && A[i]==A[i-1]) continue;
        int low=i+1;
        int high=A.size()-1;
        while(low<high){
            long long tempSum=long(A[i])+A[low]+A[high];
            if(tempSum<0) low++;
            else if(tempSum>0) high--;
            else if(ans.empty()) ans.push_back({A[i], A[low++], A[high--]});
            else{
                vector<int> temp=ans.back();
                if(temp[0]==A[i] && temp[1]==A[low] && temp[2]==A[high]);
                else ans.push_back({A[i], A[low], A[high]});
                low++; 
                high--;
            }
        }
    }
    return ans;
}