数组中和为 0 的三个数

题目描述

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a ,b ,c ,使得 a + b + c = 0 ?请找出所有和为 0 且 不重复 的三元组。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/1fGaJU
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

示例

示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]

示例 2:
输入:nums = []
输出:[]

示例 3:
输入:nums = [0]
输出:[]

方法

此题为剑指 Offer II 006. 排序数组中两个数字之和的升级版。因此我们需要在两个数字和的基础上再增加一层for循环,然后利用双指针确定剩余两个数。
当n < 3时,直接返回空。
由于要删除重复的三元组,因此我们首先对数组进行排序,然后用for循环定第一个数first,用双指针second和third定后两个数。
特殊处理:
我们利用 in 判断是否当前求得的三元组已经存在于ans数组中。

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        ans = []
        n = len(nums)
        if n < 3:
            return []
        nums = sorted(nums)
        for first in range(n-2):
            if first > 0 and nums[first] == nums[first-1]:
                continue
            res = -nums[first]
            second = first + 1
            third = n - 1
            while second < third:
                target = nums[second] + nums[third]
                if target == res:
                	#重复三元组判断操作
                    if not [nums[first], nums[second], nums[third]] in ans:
                        ans.append([nums[first], nums[second], nums[third]])
                    second += 1
                    third -= 1
                elif target > res:
                    third -= 1
                else:
                    second += 1   
        return ans
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值