|
| 1 | +/** |
| 2 | + * @param {number[]} nums |
| 3 | + * @return {number[][]} |
| 4 | + */ |
| 5 | +var threeSum = function (nums) { |
| 6 | + const sorted = nums.sort((a, b) => a - b); |
| 7 | + const result = []; |
| 8 | + |
| 9 | + for (let i = 0; i < sorted.length; i++) { |
| 10 | + const fixedNumber = sorted[i]; |
| 11 | + const previousFixedNumber = sorted[i - 1]; |
| 12 | + |
| 13 | + if (fixedNumber === previousFixedNumber) { |
| 14 | + continue; |
| 15 | + } |
| 16 | + |
| 17 | + let [leftEnd, rightEnd] = [i + 1, sorted.length - 1]; |
| 18 | + |
| 19 | + while (leftEnd < rightEnd) { |
| 20 | + const sum = fixedNumber + sorted[leftEnd] + sorted[rightEnd]; |
| 21 | + |
| 22 | + if (sum === 0) { |
| 23 | + result.push([sorted[leftEnd], sorted[rightEnd], sorted[i]]); |
| 24 | + |
| 25 | + while ( |
| 26 | + sorted[leftEnd + 1] === sorted[leftEnd] || |
| 27 | + sorted[rightEnd - 1] === sorted[rightEnd] |
| 28 | + ) { |
| 29 | + if (sorted[leftEnd + 1] === sorted[leftEnd]) { |
| 30 | + leftEnd += 1; |
| 31 | + } |
| 32 | + |
| 33 | + if (sorted[rightEnd - 1] === sorted[rightEnd]) { |
| 34 | + rightEnd -= 1; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + leftEnd += 1; |
| 39 | + rightEnd -= 1; |
| 40 | + } else if (sum < 0) { |
| 41 | + leftEnd += 1; |
| 42 | + } else { |
| 43 | + rightEnd -= 1; |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + return result; |
| 49 | +}; |
| 50 | + |
| 51 | +/** |
| 52 | + * Time Complexity: O(n^2) |
| 53 | + * The algorithm involves sorting the input array, which takes O(n log n) time. |
| 54 | + * The main part of the algorithm consists of a loop that runs O(n) times, and within that loop, there is a two-pointer technique that runs in O(n) time. |
| 55 | + * Thus, the overall time complexity is O(n log n) + O(n^2), which simplifies to O(n^2). |
| 56 | + * |
| 57 | + * Space Complexity: O(n) |
| 58 | + * The space complexity is O(n) due to the space needed for the sorted array and the result array. |
| 59 | + * Although the sorting algorithm may require additional space, typically O(log n) for the in-place sort in JavaScript, the dominant term is O(n) for the result storage. |
| 60 | + */ |
0 commit comments