Leetcode - Medium - 15. 3Sum - Javascript
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]]
such that i != j
, i != k
, and j != k
, and nums[i] + nums[j] + nums[k] == 0
.
Notice that the solution set must not contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]]
Example 2:
Input: nums = [] Output: []
Example 3:
Input: nums = [0] Output: []
Constraints:
0 <= nums.length <= 3000
-105 <= nums[i] <= 105
/** * @param {number[]} nums * @return {number[][]} */ var threeSum = function(nums) { let result = []; const numsLen = nums.length; if (numsLen < 3) { return result; } nums.sort((a,b) => a-b); for (let a = 0; a < numsLen; a++) { if(nums[a] > 0){ break; } if (a > 0 && nums[a] === nums[a-1]) { continue; } let b = a + 1; let c = numsLen - 1; const temp = -(nums[a]); while (b < c) { if (nums[a] + nums[b] + nums[c] === 0) { result.push([nums[a], nums[b], nums[c]]); while(b < c && nums[b] === nums[b+1]) b++; while(b < c && nums[c] === nums[c-1]) c--; b++; c--; } const twoPointSum = nums[b] + nums[c]; if (twoPointSum > temp) { c--; } else if (twoPointSum < temp) { b++; } } } return result; };