【Inscription 18】——"The Sum of Four Numbers"

Offer arrives, dig friends to pick up! I am participating in the 2022 Spring Recruitment Check-In Event, click to view the event details .

1. Topic description:

  1. Sum of Four - Medium Difficulty

You are given an array nums of n integers, and a target value target . Please find and return the quadruple [nums[a], nums[b], nums[c], nums[d]] that satisfies all the following conditions and does not repeat (if the two quadruple elements correspond one-to-one , the two quadruplets are considered duplicates):

0 <= a, b, c, d < na, b, c and d are different nums[a] + nums[b] + nums[c] + nums[d] == target you can return the answers in any order .

 

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]]  

hint:

1 <= nums.length <= 200

-10^9 <= nums[i] <= 10^9

-10^9 <= target <= 10^9

2. Analysis of topics and ideas:

Returning an array equal to the target value is actually similar to the sum of the three numbers. If you think of it this way, you can add double pointers in a loop.

But when I actually wrote it, I found that it is still different from the three numbers. When there are three numbers, the number with the current subscript i of the for loop is the first number, and then the subscript is the array after i, and the first value is subscripted The subscript of left and the last value is right, adding up a total of three values. If the result is greater than the target value, the subscript of the last value is subtracted. If the result is less than the target value, the subscript of the previous value is added. It is guaranteed that every combination will be taken into account.

So where does the fourth number of the sum of four numbers come from?

I originally thought that the fourth number is the next number of the first number, that is, the number with the subscript i+1, but when I actually wrote it, I found that the second number should not always be next to the first number, such as [1,2,3,4,5,6,7], if the desired result is [1,3,5,7], then press the index i,i+1,left,right to get it, never There will be correct answers, so it shouldn't matter where the four numbers might be.

So what to think about it?

We can denote the fourth number subscript by j, and the value range of j is between left and right, that is, left < j < right.

After thinking about the logic, the rest is to write the code several times before passing the code.

3. Code:

The code is implemented as follows:

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[][]}
 */
var fourSum = function(nums, target) {
    const length = nums.length
    if(nums == null || length < 4){
        return []
    }
    let arr = [] // 声明空数组
    nums.sort((a, b) => a - b) // 数组从小到大进行排序
    // console.log(nums)
    for (let i = 0; i < length ; i++) { // 确定第一个数字,初始值为nums[0]
        if(nums[i] > target && !(nums[i]<0 && target<0)){ // 如果最小数字大于target,那么和也一定大于target, 负数应该除外
            break
        }
        if(i > 0 && nums[i] == nums[i-1]){ // 当前数字与上个数字相同,说明已经循环过了,跳出本次循环
            continue
        }
        let left = i+1  // 确定第二个数字,初始值为nums[1]
        let right = length-1 // 确定第四个数字,初始值为最后一个数字
        while(left < right-1){
            let j = left+1 // 确定第三个数字,初始值为第二个数字和第四个数字中间的第一个数字
            while(j<right){
                // console.log(i, left, j, right)
                const sum = nums[i] + nums[left] + nums[j] + nums[right]
                // console.log(sum, target)
                if(sum == target){
                    // console.log(i, left, j, right)
                    arr.push([nums[i], nums[left], nums[j], nums[right]])
                    j++
                    while(j<right && nums[j] == nums[j-1]){
                        // console.log('跳过',j)
                        j++ 
                    }
                }else if (sum > target){
                    right--
                // }else if (sum < target){
                //     j++
                }else{
                    j++
                }
            }
            while (left<right && nums[left] == nums[left+1]){
                left++  
            }
            left++
            right = length-1
        }
    }        
    return arr
};

复制代码

4. Summary:

Originally, I thought that the problem-solving logic was no longer a problem, and the code should be written quickly. But writing code is always thoughtless, just like logic is just an outline, a way, and the process of writing code is not simpler than thinking about logic, and it is full of bumps and traps.

Come on!

image.png

Guess you like

Origin juejin.im/post/7079352167458406413