Leetcode15 sum of three numbers

Violence solve this problem definitely out. .

Reference god right way, the time complexity is O (n ^ 2), the spatial complexity is O (1).

The practice is still thinking of double-pointer, this is not a two-pointer to start from scratch, because the number is three, so the first fixed a number, and then do a double pointer to traverse the remaining part of this number.

So, the first natural thought to be sorted. . Then sorted in advance may be stopped during traversal, traverse to stop with the proviso that the element is greater than zero.

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        
        n=len(nums)
        res=[]
        if(not nums or n<3):
            return []
        nums.sort()
        res=[]
        for i in range(n):
            if(nums[i]>0):
                return res
            if(i>0 and nums[i]==nums[i-1]):
                continue
            L=i+1
            R=n-1
            while(L<R):
                if(nums[i]+nums[L]+nums[R]==0):
                    res.append([nums[i],nums[L],nums[R]])
                    while(L<R and nums[L]==nums[L+1]):
                        L=L+1
                    while(L<R and nums[R]==nums[R-1]):
                        R=R-1
                    L=L+1
                    R=R-1
                elif(nums[i]+nums[L]+nums[R]>0):
                    R=R-1
                else:
                    L=L+1
        return res

作者:zhu_shi_fu
链接:https://leetcode-cn.com/problems/3sum/solution/pai-xu-shuang-zhi-zhen-zhu-xing-jie-shi-python3-by/
来源:力扣(LeetCode)

 

Published 96 original articles · won praise 22 · views 40000 +

Guess you like

Origin blog.csdn.net/qq_20880939/article/details/104072425