Leetcode15. Python implementation of sum of three

Time:2021-7-28
  • Title Requirements:

Leetcode15. Python implementation of sum of three

  • thinking

    • Define a res [] to save the result set
    • First arrange the array in order, so that if you encounter duplicate numbers, you can directly go to the next one
    • Traversing the array, only traversing the position of the array subscript from 0 to the position of the array length – 2
    • If the sum of nums [i] + nums [i + 1] + nums [i + 2] is greater than 0, it means that the sum of three elements of all elements after the current traversal position must be greater than 0, because the array is in good order. At this time, break loops out
    • If the sum of the current element and the last two elements of the array is less than zero, it means that the current element is too small, and the sum of the maximum two numbers is less than zero. At this time, directly traverse the next array element (continue)
    • If the array subscript is greater than 0, and if the current element is equal to the previous element, directly traverse the next array element (continue)
    • Define an L (left) in the loop. The value of L is the next subscript i of the current array element. Define an R (right), which is the last bit of the array element, that is, Num [i] is the current value. The remaining two values should be found from left to right, from right to left to the middle, until l coincides with R
    • When traversing the array elements on the right side of I with L and R, define a TMP to save the sum of the current num [i], Num [l], Num [R]

      • If the current TMP is equal to 0, it means that three numbers are found. Append the array composed of [num [i], Num [l], Num [R]] to the res result set, and then use the while loop to find the subscript of the next array element that is not equal to the current num [l]. The judgment condition is that l is less than l, and whether the values of the current L and the next L + 1 array elements are equal. If they are equal, add l directly, So is r
      • After the while loop for finding non repeating elements ends, the current L is the last value equal to the current num [l], so adding L is the same as adding R
      • If the current TMP value is less than 0, the current sum of R and l is too small, and l is added by one
      • If the current TMP value is greater than 0, the current sum of R and l is too large, and R minus one
    • Finally, the result set res is returned
  • Core code:
#N is the length of the array
n = len(nums)
#Used to save the result set
res = []
#Sort arrays
nums.sort()

#Traversal sorted array
for i in range(n-2):
    #If the sum of the current value and the next value and the next value is greater than 0, there will be no value equal to 0. Because the array is in good order, the loop will jump out
    if nums[i] + nums[i+1] + nums[i+2] > 0:
        break
    #If the sum of the current value and the last two values of the array is less than 0, it indicates that the current value is too small. Continue to traverse the next element
    if nums[i] + nums[n-2] + nums[n-1] < 0:
        continue
    #If the subscript of the current element is not 0, and the value of the current element is equal to that of the previous element, it indicates that the element is repeated and directly traverses the next element
    if i > 0 and nums[i] == nums[i-1]:
        continue
    #L is used to represent the next element of I, R is used to represent the last element of the array, R and l move closer to the center, and look for elements with subscripts I, R, l and 0
    l = i + 1
    r = n - 1
    #When l is less than R, cycle
    while l < r:
        #Define a TMP to save the sum of the current three numbers
        tmp = nums[i] + nums[l] + nums[r]
        #If and are 0
        if tmp == 0:
            #And 0 indicates that three numbers are found. These three numbers are added to the result set as an entire array
            res.append([nums[i],nums[l],nums[r]])
            #Then judge whether the next bit of L is repeated. If l is repeated, add one
            while l < r and nums[l] == nums[l+1]:
                l += 1
            #The current num [l] is the last value equal to the previous num [l], so l needs to be added
            l += 1
            #R is the same
            while l < r and nums[r] == nums[r-1]:
                r -= 1
            r -= 1
        #If the sum of the three numbers is less than 0, it means that the sum of the three numbers is too small, and l should move to the right
        elif tmp < 0:
            l += 1
        #If the sum of the three numbers is greater than 0, it means that the sum of the three numbers is too large and R moves to the left
        else:
            r -= 1
#Return result set
return res
  • Full code:
class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """  
        n = len(nums)
        res = []
        nums.sort()

        for i in range(n-2):
            if nums[i] + nums[i+1] + nums[i+2] > 0:
                break
            if nums[i] + nums[n-2] + nums[n-1] < 0:
                continue
            if i > 0 and nums[i] == nums[i-1]:
                continue
            l = i + 1
            r = n - 1
            while l < r:
                tmp = nums[i] + nums[l] + nums[r]
                if tmp == 0:
                    res.append([nums[i],nums[l],nums[r]])
                    while l < r and nums[l] == nums[l+1]:
                        l += 1
                    l += 1
                    while l < r and nums[r] == nums[r-1]:
                        r -= 1
                    r -= 1
                elif tmp < 0:
                    l += 1
                else:
                    r -= 1
            
        return res

Recommended Today

VBS obtains the operating system and its version number

VBS obtains the operating system and its version number ? 1 2 3 4 5 6 7 8 9 10 11 12 ‘************************************** ‘*by r05e ‘* operating system and its version number ‘************************************** strComputer = “.” Set objWMIService = GetObject(“winmgmts:” _  & “{impersonationLevel=impersonate}!\\” & strComputer & “\root\cimv2”) Set colOperatingSystems = objWMIService.ExecQuery _  (“Select * from […]