|
| 1 | +/** |
| 2 | + 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. |
| 3 | + |
| 4 | + Notice that the solution set must not contain duplicate triplets. |
| 5 | + |
| 6 | + |
| 7 | + |
| 8 | + Example 1: |
| 9 | + Input: nums = [-1,0,1,2,-1,-4] |
| 10 | + Output: [[-1,-1,2],[-1,0,1]] |
| 11 | + Explanation: |
| 12 | + nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. |
| 13 | + nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. |
| 14 | + nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. |
| 15 | + The distinct triplets are [-1,0,1] and [-1,-1,2]. |
| 16 | + Notice that the order of the output and the order of the triplets does not matter. |
| 17 | + |
| 18 | + Example 2: |
| 19 | + Input: nums = [0,1,1] |
| 20 | + Output: [] |
| 21 | + Explanation: The only possible triplet does not sum up to 0. |
| 22 | + |
| 23 | + Example 3: |
| 24 | + Input: nums = [0,0,0] |
| 25 | + Output: [[0,0,0]] |
| 26 | + Explanation: The only possible triplet sums up to 0. |
| 27 | + |
| 28 | + |
| 29 | + Constraints: |
| 30 | + - 3 <= nums.length <= 3000 |
| 31 | + - -10^5 <= nums[i] <= 10^5 |
| 32 | + */ |
| 33 | +class Solution { |
| 34 | + func threeSum(_ nums: [Int]) -> [[Int]] { |
| 35 | + var res: [[Int]] = [] |
| 36 | + let sortedNums = nums.sorted(by: <) |
| 37 | + for i in 0..<sortedNums.count { |
| 38 | + if sortedNums[i] > 0 { |
| 39 | + break |
| 40 | + } |
| 41 | + // Remove duplicate element. |
| 42 | + if i > 0 && sortedNums[i] == sortedNums[i - 1] { |
| 43 | + continue |
| 44 | + } |
| 45 | + var left = i + 1 |
| 46 | + var right = sortedNums.count - 1 |
| 47 | + while left < right { |
| 48 | + if sortedNums[i] + sortedNums[left] + sortedNums[right] == 0 { |
| 49 | + res.append([sortedNums[i], sortedNums[left], sortedNums[right]]) |
| 50 | + |
| 51 | + // Remove duplicate element. |
| 52 | + while left < right && sortedNums[right] == sortedNums[right - 1] { |
| 53 | + right -= 1 |
| 54 | + } |
| 55 | + while left < right && sortedNums[left] == sortedNums[left + 1] { |
| 56 | + left += 1 |
| 57 | + } |
| 58 | + |
| 59 | + left += 1 |
| 60 | + right -= 1 |
| 61 | + } else if sortedNums[i] + sortedNums[left] + sortedNums[right] > 0 { |
| 62 | + right -= 1 |
| 63 | + } else { |
| 64 | + left += 1 |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + return res |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +let s = Solution() |
| 73 | +let r = s.threeSum([-1,0,1,2,-1,-4]) |
| 74 | +print(r) |
0 commit comments