Task4:三数之和

题目

给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

解题

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        n=len(nums)
        res=[]
        if(not nums or n<3):  # 边界检测是否存在空列表或者长度小于3的列表
            return []
        nums.sort()     # 列表排序
        res=[]
        for i in range(n):
            if(nums[i]>0):  # 边界检测,第一个元素是否大于0
                return res
            if(i>0 and nums[i]==nums[i-1]): # 重复元素跳过
                continue
            L=i+1    # 设置双指针,最左端和左右端(不包括最小数num[i])
            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): # 大于0,右端指针左移
                    R=R-1
                else:            # 小于0,左端指针右移
                    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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

发布了5 篇原创文章 · 获赞 0 · 访问量 108

猜你喜欢

转载自blog.csdn.net/weixin_43535441/article/details/104663737