Learn python every day - try to calculate the sum of four numbers

introduction:

In algorithms, the sum of four numbers is a very typical problem. The problem is mainly to find four numbers in an array so that their sum is equal to the given target value target. This article will introduce a solution to optimize time complexity.

topic:

You are given an array nums consisting of n integers, and a target value target. Please find and return the non-duplicate quadruples [nums[a], nums[b], nums[c], nums[d]] that meet all the following conditions (if the two quadruple elements correspond one-to-one , then the two quadruples are considered repeated):

0 <= a, b, c, d < n
a, b, c and d are different from each other
nums[a] + nums[b] + nums[c] + nums[d] == target
You can return in any order Answer.

Example 1:

Input: nums = [1,0,-1,0,-2,2], target = 0
Output: [[-2,-1,1,2],[-2,0,0,2],[ -1,0,0,1]]

Example 2:

Input: nums = [2,2,2,2,2], target = 8
 Output: [[2,2,2,2]]

Before we start introducing the solution, we need to understand some basic knowledge about the sum of four numbers problem. First, we need to sort this array to facilitate subsequent pruning operations; second, we need to pay attention to deduplication, because there cannot be duplicate quadruples; finally, we need to use pruning operations to improve the efficiency of the algorithm.

Idea:

According to the question requirements, we need to find out that the sum of four numbers is equal to the target value, so we can use double pointers to solve the problem. Specific steps are as follows:

  1. Sort the array;
  2. Traverse the array and judge each number. If the current minimum value is greater than the target, there is no need to continue searching and exit the loop directly; if the current maximum value is less than the target, skip directly and proceed to the next number traversal;
  3. Deduplication, if the current number is the same as the previous number, skip this loop directly;
  4. Traverse all the numbers after the current number in the array and judge each number. If the current minimum value is greater than the target, there is no need to continue searching and exit the loop directly; if the current maximum value is less than the target, skip directly and proceed to the next number. traverse;
  5. Deduplication, if the current number is the same as the previous number, skip this loop directly;
  6. Use double pointers to search from the first number after the current number to the last number. If the sum of the four numbers is equal to the target value, add it to the result set and move the left and right pointers at the same time; if the sum of the four numbers is less than the target value , move the left pointer; if the sum of the four numbers is greater than the target value, move the right pointer.

process:

The specific implementation can be seen in the code. It should be noted that in order to improve efficiency, pruning operation is required during search, that is, by comparing the relationship between the current minimum and maximum values ​​and the target to determine whether the search needs to continue. In addition, in order to prevent duplicate quadruples, deduplication operations are also required.

Code:

class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        res = []
        n = len(nums)
        nums.sort()

        for i in range(n):
            # 剪枝1:若当前最小值大于target,则无需继续搜索
            if nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target:
                break

            # 剪枝2:若当前最大值小于target,则直接跳过
            if nums[i] + nums[n-1] + nums[n-2] + nums[n-3] < target:
                continue

            # 去重
            if i > 0 and nums[i] == nums[i-1]:
                continue

            for j in range(i+1, n):
                # 剪枝3:若当前最小值大于target,则无需继续搜索
                if j+2 < n and nums[i] + nums[j] + nums[j+1] + nums[j+2] > target:
                    break

                # 剪枝4:若当前最大值小于target,则直接跳过
                if nums[i] + nums[j] + nums[n-1] + nums[n-2] < target:
                    continue

                # 去重
                if j > i+1 and nums[j] == nums[j-1]:
                    continue

                left, right = j+1, n-1
                while left < right:
                    sum_ = nums[i] + nums[j] + nums[left] + nums[right]
                    if sum_ == target:
                        res.append([nums[i], nums[j], nums[left], nums[right]])
                        left += 1
                        right -= 1

                        # 去重
                        while left < right and nums[left] == nums[left-1]:
                            left += 1
                        while left < right and nums[right] == nums[right+1]:
                            right -= 1

                    elif sum_ < target:
                        left += 1

                    else:
                        right -= 1

        return res

Extension:

When solving the sum of four numbers problem, we used double pointers and pruning operations to optimize the algorithm complexity. This method can also be applied to other similar problems, such as the sum of three numbers, the sum of two numbers, etc. At the same time, when solving problems, we need to pay attention to the selection of data structures and analysis of algorithm complexity in order to find the optimal solution.

Summarize:

Through the introduction of this article, we understand how to solve the sum of four numbers problem and learn

An in-depth approach to optimization algorithms. When solving problems, we can improve the efficiency of the algorithm through sorting, double pointers, pruning, etc., and we should also consider memory usage and code readability.

In addition, when writing blogs, we should also pay attention to structure and expression to make it easier for readers to understand and accept our content. Good text and pictures can make readers more enjoyable to read. At the same time, attention should also be paid to the format and comments of the code so that readers can better understand and use the code.

In short, as computer bloggers, we need to continuously improve our algorithm level and writing expression skills, so that we can better serve readers and gain recognition and support from more people.

Remember to click and follow! ! ! !

It’s still your Xiao Xiao! ! ! ! !

Supongo que te gusta

Origin blog.csdn.net/m0_55813592/article/details/130735425
Recomendado
Clasificación