This is the first day of my participation in the August More Text challenge

background

Himself is a front-end program apes, engaged in ordinary work every day, envy those who can into the giant’s bosses, always feel confused, also want to into the metal, so we consulted some bosses, learned through the bosses into giant need inspect algorithm problem, so I started my journey to brush algorithm, but I find classmates very little written in js algorithm, I found it difficult to find what I wanted, so I wanted to write a record of brushing algorithm problems to record my own journey, and also hope to help some other friends who were also confused. Here is from the most simple start, step by step, forward!!

LeetCode sum of two numbers

Topic describes

Given an integer array nums and an integer target value target, find the two integers in the array and the target value target and return their array subscripts.

You can assume that there is only one answer for each type of input. However, the same element in the array cannot be repeated in the answer.

You can return the answers in any order.

Example 1:

Enter nums = [2,7,11,15], target = 9

Output: [0, 1]

Because nums[0] + nums[1] == 9, return [0, 1]

Example 2:

Enter: nums = [3,2,4], target = 6

Output: [1, 2]

Example 3:

Enter: nums = [3,3], target = 6

Output: [0, 1]

Their thinking

For example, if you use the “for” loop, then use the “if” loop, then use the “for” loop, then use the “if” loop.

var twoSum = function(nums, target) { 
    let a,b 
    nums.forEach((item,index) = > { 
        for(i=index+1; i<nums.length; i++){if(item+nums[i]===target){ 
                a =index b=i
            }
        }
    })
    return [a,b] 
};
Copy the code

Num = target-nums[index]; if num = target-nums[index]; if num = target-nums[index]; But by trying, I found that there is a more advanced way

 var twoSum = function(nums, target) { 
    let a let b 
    for(index=0; index<nums.length; index++) {let num = target-nums[index] 
        if(nums.indexOf(num)! = = -1){ 
            a=index 
            b=nums.indexOf(num) 
        }
        if(a! ==b){return [a,b]
        } 
    }
};
Copy the code

Idea 3: [I] = target nums[I] = target nums[I] Get (complement), I] returns [map.get(complement), I]. If not, add the value to the map using the set method

var twoSum = function(nums, target) { 
    const map = new Map(a)for(let i=0; i<nums.length; i++){const complement = target - nums[i] 
        if(map.has(complement)){ 
            return [map.get(complement),i] 
        }else{
            map.set(nums[i],i) 
        } 
    } 
    return[]}.Copy the code

conclusion

There is no best algorithm, only better algorithm, although this is a simple sum of two numbers, but it contains a lot, learning algorithm road, road resistance and long, from easy to difficult, from simple to complex, step by step forward, come on!!

If you have different views, welcome to comment on it.