3 sum

问题:寻找数组中3个和为0的所有数字组合,要求不能重复

示例:

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

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

解决思路:固定其中一个数,对另外两个数进行考察

Python代码:

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

 

posted @ 2019-03-24 12:40  秦qin  阅读(330)  评论(0编辑  收藏  举报