题目

解题

def threeSum(nums):
    nums.sort()  # 首先对数组进行排序
    result = []  # 用于存储最终结果的列表

    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            # 避免重复的三元组
            continue

        left, right = i + 1, len(nums) - 1

        while left < right:
            total = nums[i] + nums[left] + nums[right]

            if total < 0:
                left += 1
            elif total > 0:
                right -= 1
            else:
                # 找到一个和为0的三元组
                result.append([nums[i], nums[left], nums[right]])

                # 跳过重复的元素
                while left < right and nums[left] == nums[left + 1]:
                    left += 1
                while left < right and nums[right] == nums[right - 1]:
                    right -= 1

                # 移动到下一个不同的元素
                left += 1
                right -= 1

    return result


# 示例
nums = [-1, 0, 1, 2, -1, -4]
print(threeSum(nums))
08-12 15:05