|
| 1 | +var threeSum = function(nums) { |
| 2 | + // sort the array |
| 3 | + nums = nums.sort((a, b) => a - b); |
| 4 | + |
| 5 | + let result = []; |
| 6 | + // iterate through the array and use two pointers to find the sum |
| 7 | + for (let i = 0; i < nums.length; ++i) { |
| 8 | + let left = i + 1; |
| 9 | + let right = nums.length - 1; |
| 10 | + while (left < right) { |
| 11 | + let sum = nums[i] + nums[left] + nums[right]; |
| 12 | + if (sum == 0) { |
| 13 | + result.push([nums[i], nums[left], nums[right]]); |
| 14 | + left++; |
| 15 | + right--; |
| 16 | + } |
| 17 | + else if (sum < 0) { |
| 18 | + left++; |
| 19 | + } |
| 20 | + else { |
| 21 | + right--; |
| 22 | + } |
| 23 | + } |
| 24 | + // skip duplicates |
| 25 | + while (i < nums.length - 1 && nums[i] == nums[i + 1]) { |
| 26 | + i++; |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + // initialize set to remove duplicate |
| 31 | + const set = new Set(result.map(JSON.stringify)); |
| 32 | + // final output array |
| 33 | + output = (new Array(...set).map(JSON.parse)); |
| 34 | + return output; |
| 35 | +}; |
| 36 | + |
| 37 | + |
| 38 | +module.exports = threeSum; |
| 39 | + |
0 commit comments