This is the second day of my participation in Gwen Challenge


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]

Tip:

2 <= nums.length <= 104-109 <= nums[I] <= 109-109 <= target <= 109

Advanced: Can you think of an algorithm whose time complexity is less than O(n2)?

The original problem

Train of thought

  • A hashMap is used to store the iterated elements and their corresponding indexes.

  • Each element is iterated over to see if there is a target number in the hashMap that meets the requirements.

  • Everything is done in one traverse (space for time).

    / * * *@param {number[]} nums
     * @param {number} target
     * @return {number[]}* /
    var twoSum = function(nums, target) {
          const mp = {};                    // Store the number that appears, and the corresponding index
        for (let i = 0; i < nums.length; i++) {       // Iterate over the elements
            const targetNum = target - nums[i];          // The target element satisfies the requirement
            const targetIndex = mp[targetNum]; // Get the index of the target element in mp
            if(targetIndex ! = =undefined) {         // If present, return [index of target element, current index]
                return [targetIndex, i];
            } else {                                    // If it does not exist, the target element was not present before
                mp[nums[i]] = i;                     // Store the current element and the corresponding index}}return[]; }; or/ * * *@param {number[]} nums
     * @param {number} target
     * @return {number[]}* /
    var twoSum = function(nums, target) {
        const mp = new Map(a);for(let i = 0; i<nums.length; i++){let res = target-nums[i];
            if(mp.has(res)){
                 return [i,mp.get(res)];
             }
                mp.set(nums[i],i);
        }
        return [];
    };
    Copy the code

    Didi di, leave a thumbs-up before you go, if the big guy has any new or other ideas, welcome to point out. 🌀