A good way to determine if the sum of two numbers in an array is a given value is to swap space for time and use a Map to store it.

The title

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 an array cannot be used twice.

You can return the answers in any order.

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

var twoSum = function (nums, target) { let len = nums.length; const MAP = new Map(); Map.set (nums[0], 0); for (let i = 1; i < len; I ++) {let other = target-nums [I]; // Return the corresponding subscript if (map.get (other)! == undefined) return [MAP.get(other), i]; Set (nums[I], I)}}; let tempRes = twoSum([1, 2, 3, 4, 5, 9], 10); console.log(tempRes);Copy the code

Map

A Map can be used to hold key-value pairs. Any value can be a key or value, such as an object or an array.

Can I use Object?

It is best to use a Map because the keys in a Map are ordered, and when iterated, a Map object returns the keys in the order they were inserted. In newer browsers, using Object in this topic is generally ok because, since ECMAScript2015, iterating over string only objects produces keys in insertion order, but also requires converting numeric types to string types.