Sum of three numbers (simple and easy to understand)

Sum of three numbers (simple and easy to understand)

Question : Given an array nums containing n integers, determine whether there are three elements a, b, c in nums such that a + b + c = 0? Please find all triples that meet the conditions and are not repeated.

Note: Answers cannot contain duplicate triples.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

The set of triples that meets the requirements is: [ [-1, 0, 1], [-1, -1, 2] ]

Difficulty : The difficulty of this question is how to remove duplicate solutions .
Usage method : Double pointers.
Basic idea : fix one position, and use double pointers to move the other two positions. Execution
steps :

  • Remove special cases. For the case where the array length is less than 3 and the array is empty, [] is returned directly.
  • Sort the array from small to large (to facilitate pruning and remove duplicates)
  • Traverse the sorted array. At this time, i is the fixed position. Each traversal uses a double pointer.
    • If the elements currently pointed to by i are all greater than 0, it is impossible to have three numbers = 0 (because the array is sorted, and the current i is the smallest value among the three numbers)
    • If i traverses to repeated elements, it will be skipped to avoid repeated solutions.
    • Let the left pointer l=i+1 and the right pointer r=n-1 (the left pointer points to the next bit of i currently traversed; the right pointer points to the end, traversing from back to front), when l<r, execute the loop
      • sum=nums[i]+nums[l]+nums[r], if equal to 0, add the value of the index position corresponding to the result to the result set. Don’t forget to deduplicate and shift the left and right pointers at this time.
      • If the result sum is greater than 0, move the right pointer left
      • If the result is less than 0, move the left pointer right

executable code

class Solution():
    def threeSum(self,nums):
        n=len(nums)
        result=[]
        #如果数组为null或者长度小于3,返回[]
        if nums==None or n<3:
            return []
        #对数组进行排序
        nums.sort()  #该方法没有返回值,但是会对列表的对象进行排序
        #遍历排序后的数组
        for i in range(n):
            #如果当前i指向的元素都大于0,则不可能出现=0的三个数了
            if nums[i]>0:
                return result
            # i 重复元素则跳过
            if i > 0 and nums[i]==nums[i-1]:
                continue
            #令左指针l=i+1,右指针r=n-1 
            l=i+1
            r=n-1
            # 当l<r时 ,执行循环
            while(l<r):
                sum=nums[i]+nums[l]+nums[r]
                # 如果等于0,将结果对应的索引位置的值加入结果集中
                if sum==0:
                    result.append([nums[i],nums[l],nums[r]])
                    #在将左指针和右指针移动的时候,先对左右指针的值,进行判断; 如果重复,直接跳过; 
                    #去重,因为 i 不变,当此时 l取的数的值与前一个数相同,所以不用在计算,直接跳
                    while l < r and nums[l]==nums[l+1]:
                        l+=1
                    #去重,因为 i不变,当此时 r 取的数的值与前一个相同,所以不用在计算
                    while l < r and nums[r]==nums[r-1]:
                        r-=1
                    #将 左指针右移,将右指针左移
                    l+=1
                    r-=1
                # 如果结果大于0,将右指针左移
                elif sum>0:
                    r-=1
                #如果结果小于0,将左指针右移
                else:
                    l+=1

        return result

Note :

  1. The deduplication operations of the fixed position i and the left and right pointers are different.
    Fixed position: nums[i]==nums[i-1]
    Left pointer: nums[l]==nums[l+1]
    Right pointer: nums[r]= =nums[r-1]
    Reason : This is because when deduplicating fixed positions, if nums[i]==nums[i+1] is used, some non-duplicate occurrences will be lost.
    For example: array [1,1 ,2]
    Use the method of nums[i]==nums[i+1]: when traversing the first 1, the next 1 will be judged as a duplicate, and the situation [1,1,2] will be skipped directly. ;
    Use nums[i]==nums[i-1]: when traversing the first 1, the next 1 will not be judged as a duplicate, and [1,1,2] will be added to the result set

What we want to do is that there cannot be repeated triples, but the elements within the triples can be repeated!

Guess you like

Origin blog.csdn.net/qq_42859625/article/details/129438246