Simple and concise C++ solution


  • 0
    R
       vector<vector<int>> threeSum(vector<int>& nums) {
        int len = nums.size();
        vector<vector<int>> output;
        
        sort(begin(nums), end(nums));
        
        for(int p1 = 0; p1 < len - 2; ++p1) {
            if(p1 != 0 && (nums[p1 - 1] == nums[p1])) continue;
            if(nums[p1] + nums[p1 + 1] + nums[p1 + 2] > 0) break;
            for(int p2 = p1 + 1, p3 = len - 1; p2 < p3;) {
                if(p2 != p1 + 1 && nums[p2 - 1] == nums[p2]) {
                    ++p2; 
                    continue;
                }
                if(p3 != len - 1 && nums[p3] == nums[p3 + 1]) {
                    --p3;
                    continue;
                }
                
                int sum = nums[p1] + nums[p2] +nums[p3];
                if(sum == 0) {
                    output.push_back({nums[p1], nums[p2], nums[p3]});
                    ++p2, --p3;
                }
                else if(sum < 0) ++p2;
                else --p3;
            }
        }
        return output;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.