[LeetCode] 3Sum 三数之和 Python

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jerry81333/article/details/76020793

刚开始刷题,各方面都觉得很不成熟,总是被Time Limited,特此总结下失败的思维和成功的思维。

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.

For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]


简单说,题目就是要三数之和等于0,并且答案数组中不能出现重复的答案。

最简单的解决方案:

i=0开始遍历第一个数,j=i+1开始遍历第二个数,x=j+1开始遍历第三个数。并且在加入答案数组前,进行Sort()后遍历答案数组,看是否有相同的。(最后导致time limited)
虽然失败了,但是还是贴上代码,作为一种最愚蠢的解决方案:

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        i=0
        x=0
        first=[]
        while(i<len(nums)):
            j=i+1
            #temp=[]
            while(j<len(nums)):
                #temp.append(nums[i]+nums[j])
                #sum1=nums[i]+nums[j]
                x=j+1
                while(x<len(nums)):
                    if(nums[i]+nums[j]+nums[x]==0):
                        y=0
                        while(y<len(first)):
                            temp=[nums[i],nums[j],nums[x]]
                            first[y].sort()
                            temp.sort()
                            if(first[y]==temp):
                                y=-1
                                break
                            y+=1
                        if(y!=-1):
                            first.append([nums[i],nums[j],nums[x]])
                    x+=1
                j+=1
            i+=1
        return first


最终解决方案:

最终将3Sum拆解为2Sum+X,2Sum可以先排序,然后再用收尾慢慢收缩的方式寻找target,并且可以在寻找时剔除相同的left,right,时间复杂度因为O(N)。在3Sum中,则需要每个nums[]中的元素都作为X一次,因此O(N^2),比上方最起码的O(N^3)要好不少。

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        first=[]
        i=0
        while(i<len(nums)-2):
            if(nums[i]!=nums[i-1] or i==0):
                target=0-nums[i]
                left=i+1
                right=len(nums)-1
                while(left!=right):
                    if(nums[left]+nums[right]==target):
                        first.append([nums[i],nums[left],nums[right]])
                        while(left<right):
                            left+=1
                            if(nums[left]!=nums[left-1]):
                                break
                        while(right>left):
                            right-=1
                            if(nums[right]!=nums[right+1]):
                                break
                    elif(nums[left]+nums[right]>target):
                        right-=1
                    elif(nums[left]+nums[right]<target):
                        left+=1
            i+=1
        return first


猜你喜欢

转载自blog.csdn.net/jerry81333/article/details/76020793