美文网首页
算法---在整数数组中求三个数之和为0

算法---在整数数组中求三个数之和为0

作者: reedthinking | 来源:发表于2017-07-11 19:35 被阅读0次

在一个整数数组中找出所有和为0的三元组

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'thinkreed'
__mtime__ = '2017/3/16'

"""


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

        result = []
        #排序 o(nlogn)
        nums.sort()
        i = 0

        while i < len(nums):
            #将3数之和问题转换为求两数和为target的问题
            target = 0 - nums[i]
            #预示着剩下所有数都大于0,不可能得到3个数之和为0
            if target < 0:
                break

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

            #求两数和为target
            while left < right:
                cur_sum = nums[left] + nums[right]

                if cur_sum < target:
                    left += 1
                elif cur_sum > target:
                    right -= 1
                else:
                    triple = [nums[i], nums[left], nums[right]]

                    #越过重复
                    while left < right and nums[left] == triple[1]:
                        left += 1
                    #越过重复
                    while left < right and nums[right] == triple[2]:
                        right -= 1

                    result.append(triple)
            #不计算重复值
            while i + 1 < len(nums) and nums[i + 1] == nums[i]:
                i += 1

            i += 1

        return result


if __name__ == '__main__':
    print(Solution().threeSum([-1, 0, 1, 2, -1, -4]))

相关文章

  • 求三个数和为0

    题目描述: 给定一个数组,要求在这个数组中找出 3 个数之和为 0 的所有组合。 Example: 算法思路 使用...

  • 算法---在整数数组中求三个数之和为0

    在一个整数数组中找出所有和为0的三元组

  • LeetCode 第18题:四数之和

    1、前言 2、思路 采用三数之和的思路,原本三数之和可以分解为:数组中的一个数 + 此数右边的数求两数之和,那么四...

  • 经典算法 — 两数之和

    经典算法 — 两数之和 题目描述 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目...

  • 三路快排算法-求中位数问题(4)

    算法面试高频题,求前K个数,或者求中位数 三路快排算法思路 将数组分为三部分,随机选择数组中的一个数,使数组左边都...

  • 【算法】三数之和

    【算法】三数之和 1、题目 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,...

  • LeetCode-第1题-求两数之和-题解

    求两数之和 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的 那 两个 ...

  • LeetCode题解1:Two Sum

    Two Sum问题:给定一个数组nums和一个正整数target,试从数组中找出2个元素,它们相加之和恰好为tar...

  • leetcode刷题1

    用go语言做算法题 两数之和给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的...

  • 15. 3Sum_Swift

    难度 中等 题目 给定一个整数类型的数组,其中三个数字之和等于0,以二维数组的形式返回所有符合条件的数字组合并且不...

网友评论

      本文标题:算法---在整数数组中求三个数之和为0

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