Task4: three digital sum

topic

Given an array nums n comprises integers, it determines whether there are three elements a, b, c nums such that a + b + c = 0? All the conditions are not satisfied to find duplicate triples.

Note: The answer can not contain duplicate triples.

Problem-solving

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

Author: zhu_shi_fu
link: https: //leetcode-cn.com/problems/3sum/solution/pai-xu-shuang-zhi-zhen-zhu-xing-jie-shi-python3-by/
Source: stay button (LeetCode)
copyright reserved by the authors. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.

Released five original articles · won praise 0 · Views 108

Guess you like

Origin blog.csdn.net/weixin_43535441/article/details/104663737