[Leetcode] 15.3Sum @python

题目

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},

A solution set is:
(-1, 0, 1)
(-1, -1, 2)

题目要求

在一个给定数组nums中找到所有满足a+b+c=0的不重复的三元组

解题思路

解题思路参照南郭子綦
先给数组排序,对于数组中的每个数nums[i],在i到len(nums)找到和为-nums[i]的两个数。因为要求不能有重复,所以实现过程中有多处地方需要注意防止重复。
- 在遍历nums时,相同的num只在第一次进行target寻找操作
- 在left和right指针移动时,如果移动到的位置与前一个位置的值相同,则继续向下移动

代码

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()

        ans = []
        for i in range(len(nums) - 2):
            if i == 0 or nums[i] > nums[i - 1]:
                target = -nums[i]
                left,right = i + 1,len(nums) - 1
                while left < right:
                    if nums[left] + nums[right] == target:
                        ans.append((nums[i],nums[left],nums[right]))
                        left += 1
                        right -= 1
                        while left < right and nums[left] == nums[left - 1]:left +=1
                        while left < right and nums[right] == nums[right + 1]:right -=1
                    elif nums[left] + nums[right] < target:
                        left += 1
                        while left < right and nums[left] == nums[left -1]:left += 1
                    else:
                        right -= 1
                        while left < right and nums[right] == nums[right + 1]:right -= 1

        return ans
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值