“This is the first day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021”
Topic:
1. Sum of two numbers
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:
Input: nums = [2,7,11,15], target = 9 output: [0,1]Copy the code
Example 2:
Input: nums = [3,2,4], target = 6Copy the code
Example 3:
Input: nums = [3,3], target = 6Copy the code
Tip:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
- There can only be one valid answer
Advanced: Can you think of an algorithm whose time complexity is less than O(n2)?
Ideas:
- Traversal saves all elements of the current array to the map
- Determine if the target value – current value exists in the map while saving, and save the index if so
- Traversal is over. If you don’t find it, it doesn’t exist
Implementation:
/ * * *@param {number[]} nums
* @param {number} target
* @return {number[]}* /
var twoSum = function (nums, target) {
let map = new Map(a);for (let i = 0; i < nums.length; i++) {
// Check whether the element we traversed before exists
let cur = target - nums[i];
if (map.has(cur)) {
return [map.get(cur), i];
}
// Record each element for later judgment
map.set(nums[i], i);
}
// If the loop is not found, it does not exist
return [];
};
Copy the code
If you understand it, you can click on it and see you in the next topic. If there is no accident after the article will be in this form, there are good suggestions welcome to comment area.