JS Likou classic 100 questions - the sum of two numbers

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

You can assume that there is only one answer for each input. However, the same element in the array cannot appear repeatedly in the answer.

You can return answers in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, return [0, 1].

Method 1: weak chicken for loop version

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    let arr = []
    for(let i=0; i<nums.length; i++) {
        for(let j=i+1; j<nums.length; j++) {
            if(nums[i]+nums[j] == target) {
                arr.push(i)
                arr.push(j)
                return arr
            }
        }
    }

};

Method 2: Now convert the original array into a map (key: array element, value: corresponding subscript)

When looping through, find out whether there is key=target-num[i] in the map for the i-th element num[i]

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    const map = new Map();
    for (let i=0; i<nums.length; i++){
        map.set(nums[i],i)
    }
    let arr = []
    for(let i=0; i<nums.length; i++){
        if(map.has(target-nums[i]) && i!=map.get(target-nums[i]) ){
            arr.push(i)
            arr.push(map.get(target-nums[i]))
            return arr
        }
    }
};

Method 3: Advanced version, a loop to realize the encapsulation map and search map, the idea is that the previous elements have been encapsulated in the map each time the search is performed, even if the previous elements do not find the corresponding item in the map, but when traversing later Will find it. However, it should be noted that the map must be copied after comparison, and the latter item of the duplicated key value will overwrite the previous item, resulting in the subscript of the previous one not being found when outputting.

Such as test case [3,3] 6

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    const map = new Map();
    for (let i=0; i<nums.length; i++){
        if(map.has(target-nums[i]) && i!= map.get(target-nums[i])){
            return [i,map.get(target-nums[i])]
        }
        map.set(nums[i],i)
    }
};

Guess you like

Origin blog.csdn.net/qq_36384657/article/details/128168260