首页 > 编程语言 > 详细

寻找数组中3个和为0的所有数字组合,要求不能重复(3 sum)

时间:2019-03-24 12:53:56      阅读:174      评论:0      收藏:0      [点我收藏+]

示例:

输入:[-2,3,-1,1,-1,2]

输出:[[-2,-1,3],[-1,-1,2]]

Python解决方案1:

固定其中一个数,对另外两个数进行考察

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
    
        out = []
        nums.sort()
        for i in range(len(nums)-2):
            if i > 0 and nums[i] == nums[i-1]:
                continue
            else:
                start = i + 1
                end = len(nums) - 1
                while start < end:
                    num2sum = nums[start] + nums[end]
                    if num2sum < -nums[i] or (start>i+1 and nums[start]==nums[start-1]):
                        start += 1
                    elif num2sum > -nums[i] or (end < len(nums)-1 and nums[end] == nums[end+1]):
                        end -= 1
                    else:
                        out.append([nums[i],nums[start],nums[end]])
                        start += 1
                        end -= 1
        return out

Python解决方案2:

(转自leetcode用户WangQiuc)

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        if len(nums) < 3: return []
        counter = collections.Counter(nums)
        out = [[0,0,0]] if counter[0]>2 else []
        neg, pos = [x for x in counter if x < 0], [x for x in counter if x >= 0]
        for n in range(len(neg)):
            if n > 0 and neg[n] == neg[n-1]
            for p in pos:
                x = -n-p
                if x in counter:
                    if x in [n,p] and counter[x] > 1: 
                        out.append([n,x,p])
                    elif x < n:
                        out.append([x,n,p])
                    elif x > p:
                        out.append([n,p,x])
        return out

 

寻找数组中3个和为0的所有数字组合,要求不能重复(3 sum)

原文:https://www.cnblogs.com/wenqinchao/p/10587698.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!