力扣之数组1—三数之和

十年热恋 提交于 2020-01-17 07:10:36

三数之和

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]

解题思路:
排序 + 双指针

算法流程:

  • 判断数组长度是否为空或小于3,是的话直接返回空
  • 对数组进行排序,可放置出现重复的结果
  • 遍历排序后数组:
    * 若nums[i]>0,直接返回结果,因为已经排序好了后边三数相加不可能等于0
    • 对于重复元素跳过
    • 应左指针a = i+1,右指针b = n-1,当a<b时执行循环:
      • 当 nums[i]+nums[a]+nums[b==0,执行循环,判断左边和右边是否和下一位置重复,去除重复解。并同时将a,b移到下一位置,寻找新的解,
      • 若和大于0,说明 nums[b] 太大,b左移;
      • 若和小于0,说明 nums[a] 太小,a右移

代码:

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        n = len(nums)
        result =  []
        if (not nums or n <3):
            return result
        nums.sort()
        for i in range(n):
            if nums[i] > 0:
                return result
            if i>0 and nums[i] == nums[i-1]:
                continue
            a = i + 1
            b = len(nums)-1
            while a<b:
                if nums[i] + nums[a] + nums[b] == 0:
                    result.append([nums[i],nums[a],nums[b]])
                    while a<b and nums[a] == nums[a+1]:
                        a += 1
                    while a<b and nums[b] == nums[b-1]:
                        b -= 1
                    a += 1
                    b -= 1
                elif nums[i] + nums[a] + nums[b] < 0:
                    a += 1
                else:
                    b -= 1
        return result

链接: 作者:zhu_shi_fu
链接:https://leetcode-cn.com/problems/3sum/solution/pai-xu-shuang-zhi-zhen-zhu-xing-jie-shi-python3-by/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!