Nuggets team number online, help you Offer impromptu! Click for details

1. Title Description

Given an integer array nums and an integer target value target, find the two integers in the array and the target values 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 <= 103
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • There can only be one valid answer

Source: LeetCode link: leetcode-cn.com/problems/tw…

Second, train of thought analysis

  1. Create a dictionary table Map

  2. Iterates the number group and matches the target value target-currentValue that matches the information

  3. Returns two numeric subscripts on success

  4. If a match fails, the player’s information is put into the dictionary table Map created

AC code

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

Four,

A good understanding of Map is required

Map objects :Map objects hold key-value pairs. Any value (object or raw value) can be a key or a value.

Map properties and methods

  • The size property returns the number of members of the map structure
  • Map.prototype.set(key, value) set(key, value) set(key, value) set(key, value
  • Map.prototype.get(key) GetValue, undefined
  • Map.prototype.has(key) Checks whether a Map object exists and returns a Boolean value
  • Map.prototype.delete(key) Deletes a key and returns a Boolean value
  • Map.prototype.clear() clears all members with no return value
  • Map.prototype.keys() returns the traversal key name
  • Map.prototype.values() returns the traversal key
  • Map.prototype.entries() returns all members traversed
  • Map.prototype.foreach () iterates through all members of the Map

This article is participating in the nuggets team number online activity, click to see the dachang spring recruiting positions