1. 程式人生 > >尋找數組中3個和為0的所有數字組合,要求不能重復(3 sum)

尋找數組中3個和為0的所有數字組合,要求不能重復(3 sum)

pen 數字組合 class iuc def i+1 += out art

示例:

輸入:[-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)