美文网首页
15. 三数之和

15. 三数之和

作者: 周英杰Anita | 来源:发表于2020-06-24 15:50 被阅读0次

给你一个包含 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,那么后面不可能有2个数加和等于- -nums[i],直接返回结果。
如果当前的数字和前一个数字相同,那么对于重复元素:直接跳过本次循环,避免出现重复解
令左low = i + 1, high = length - 1,当low < high,执行循环:
若nums[low] + nums[high] > -nums[i],说明总和太大,high左移
若nums[low] + nums[high] < -nums[i],说明总和太小,low 右移
若nums[low] + nums[high] == -nums[i],则将当前的元素添加到结果集中,同时执行循环,判断左界和右界是否和下一位置重复,去除重复解,并同时将 low,high移到下一位置,寻找新的解

python3解法

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        length = len(nums)
        if not nums or length < 3: return []
        nums.sort()
        ans = []
        low, high = 0, 0
        for i in range(length):
            # 由于数组已经有序,如果 nums[i]>0,那么后面不可能有2个数加和等于- -nums[i],直接返回结果。
            if nums[i] > 0 : return ans
            # 如果当前的数字和前一个数字相同,那么对于重复元素:直接跳过本次循环,避免出现重复解
            if i > 0 and nums[i] == nums[i - 1]:
                continue
            low = i + 1
            high = length - 1
            while low < high:
                if nums[low] + nums[high] > -nums[i]:
                    high -= 1
                elif nums[low] + nums[high] < -nums[i]:
                    low += 1
                else:
                    ans.append([nums[i], nums[low], nums[high]])
                    # 同时执行循环,判断左界和右界是否和下一位置重复,去除重复解
                    while low < high and nums[low] == nums[low + 1]:
                        low += 1
                    while low < high and nums[high] == nums[high - 1]:
                        high -= 1
                    low += 1
                    high -= 1
        return ans                   

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

相关文章

网友评论

      本文标题:15. 三数之和

      本文链接:https://www.haomeiwen.com/subject/esirfktx.html