C++ 49ms 11 lines with comments


  • 4
    vector<vector<int>> threeSum(vector<int>& nums) {
            sort(nums.begin(), nums.end());                                                 // keep nums in ascending order
            vector<vector<int>> ans;
            
            for (int k = 2; k < nums.size(); k++) {                                         // let i < j < k
                if (k + 1 < nums.size() && nums[k] == nums[k + 1]) { continue; }            // skip duplicates
                
                for (int i = 0, j = k - 1, sum = nums[i] + nums[j], target = 0 - nums[k]; i < j; sum = nums[i] + nums[j]) {
                    if (sum < target || (i > 0 && nums[i - 1] == nums[i])) { i++; }         // check sum and skip duplicates
                    else if (sum > target || (j + 1 < k && nums[j] == nums[j + 1])){ j--; } // check sum and skip duplicates
                    else { ans.push_back({nums[i++], nums[j--], nums[k]}); }                // record a valid set
                }
            }
            
            return ans;
    }
    

  • 0
    J

    Very concise,thx!


Log in to reply
 

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