Nuggets team number online, help you Offer impromptu! Click on theCheck the details

preface

The first time to participate in the Nuggets punch card activity, among other things, mainly rush to reward. 4.12 Start to rush to achieve the small goal of question 14!!

Topic describes

The sum of two numbers

For the title description, I mainly use the screenshot leetcode, so the title is as follows

Thought analysis

Enter an array and a target value, and find the subscript of the target value. I’m going to start with the case where there must be, and there’s only one case, and how do I get the answer, because I know and so my idea is to go through the array and then if the difference between target-item exists in the array then the index between the value and the current value is the answer that I’m going to return. Ps: But I wonder if the value of target is higher than the value of target, if the value of target is higher than the value of target, then we can ignore the value of target. Of course, if the value of target is higher than the value of target, it is wrong. So LET me do it the conventional way

Finally, I passed it through two modifications, and the idea of finding the first number is to go through the array and then look for the difference from the array after that number, if it exists, it’s the first number we want. So we have a nums.slice(index+1), and find the first number

I thought it would be easier to just find the index of the difference, okay, so I’m going to get the index of the same number wrong, so I’m going to do the reverse() thing and I’m going to find the index of the difference and I’m going to get the index of the reverse, And then the second value is equal to the length of the array -(the inverted subscript +1), I thought I had it right and then I went into a pit where the inverted array changes the value of the original array so I added arR to store the original array, and then I passed

AC code

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    let arr = [...nums]
    if(nums&&nums.length>1){
        let firstNum = nums.findIndex((item,index)=>{
            return nums.slice(index+1).includes(target-item)
        })
        if(firstNum===-1){
            return []
        }else{
            let secondNum = nums.length-nums.reverse().indexOf(target-arr[firstNum])-1
            return [firstNum,secondNum]
        }
    }else{ 
        return []
    }
};
Copy the code

conclusion

Be careful, or you’ll have a bug. Algorithm two is done. Persistence is victory

Left left left

→ Algorithm series link ←

Write write write

You can order it here! You can order it here! You can order it here!