Find all unique triplets in a sorted array of integers that sum up to zero. Args: nums: A sorted list of integers. Returns: A list of lists containing unique triplets that sum up to zero. >>> three_sum([-1, 0, 1, 2, -1, -4]) [[-1, -1, 2], [-1, 0, 1]] >>> t
(nums: list[int])
| 4 | |
| 5 | |
| 6 | def three_sum(nums: list[int]) -> list[list[int]]: |
| 7 | """ |
| 8 | Find all unique triplets in a sorted array of integers that sum up to zero. |
| 9 | |
| 10 | Args: |
| 11 | nums: A sorted list of integers. |
| 12 | |
| 13 | Returns: |
| 14 | A list of lists containing unique triplets that sum up to zero. |
| 15 | |
| 16 | >>> three_sum([-1, 0, 1, 2, -1, -4]) |
| 17 | [[-1, -1, 2], [-1, 0, 1]] |
| 18 | >>> three_sum([1, 2, 3, 4]) |
| 19 | [] |
| 20 | """ |
| 21 | nums.sort() |
| 22 | ans = [] |
| 23 | for i in range(len(nums) - 2): |
| 24 | if i == 0 or (nums[i] != nums[i - 1]): |
| 25 | low, high, c = i + 1, len(nums) - 1, 0 - nums[i] |
| 26 | while low < high: |
| 27 | if nums[low] + nums[high] == c: |
| 28 | ans.append([nums[i], nums[low], nums[high]]) |
| 29 | |
| 30 | while low < high and nums[low] == nums[low + 1]: |
| 31 | low += 1 |
| 32 | while low < high and nums[high] == nums[high - 1]: |
| 33 | high -= 1 |
| 34 | |
| 35 | low += 1 |
| 36 | high -= 1 |
| 37 | elif nums[low] + nums[high] < c: |
| 38 | low += 1 |
| 39 | else: |
| 40 | high -= 1 |
| 41 | return ans |
| 42 | |
| 43 | |
| 44 | if __name__ == "__main__": |