力扣之三数之和

问题

在这里插入图片描述

解答

将该数组nums先进行排序,设置左右指针L和R,左指针初始指向第二个元素,右指针初始指向倒数第一个元素,i指针从第一个元素起遍历nums,跳过重复项,如果三数之和相等就添加到result,去除重复项,如果三数之和大于零或小于零,R-1或L+1,最终返回结果,具体实现方法参考以下代码。

class Solution:
    def threeSum(self, nums):
        n=len(nums)
        result=[]
        if(not nums or n<3):#special cases
            return []
        nums.sort() #sort nums
        for i in range(n):
            if(nums[i]>0):
                return result #all elements in nums is positive
            if(i>0 and nums[i]==nums[i-1]):
                continue
            L=i+1 #left point
            R=n-1 #right point
            while(L<R):
                if(nums[i]+nums[L]+nums[R]==0):
                    result.append([nums[i],nums[L],nums[R]])
                    #get rid of duplicative elements
                    while(L<R and nums[L]==nums[L+1]):
                        L=L+1
                    #get rid of duplicative elements
                    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 result

击败用户

在这里插入图片描述

发布了25 篇原创文章 · 获赞 8 · 访问量 920

猜你喜欢

转载自blog.csdn.net/weixin_44617944/article/details/104641582