输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
const twoSum = function (nums, target) {
if (Object.prototype.toString.call(nums) !== '[object Array]' || typeof target !== 'number') {
alert("input type incorrect");
return;
}
const arrMap = new Map()
for (let i = 0; i < nums.length; i++) {
const result = target - nums[i];
if (arrMap.has(result)) {
return [arrMap.get(result)+1, i+1] // 这里返回值 +1
}
arrMap.set(nums[i], i)
}
};
Runtime: 48 ms, faster than 98.63% of JavaScript online submissions for Two Sum II - Input array is sorted.
Memory Usage: 35.2 MB, less than 44.43% of JavaScript online submissions for Two Sum II - Input array is sorted.
Runtime: 68 ms, faster than 38.61% of JavaScript online submissions for Two Sum II - Input array is sorted.
Memory Usage: 35.1 MB, less than 57.40% of JavaScript online submissions for Two Sum II - Input array is sorted.
Runtime: 56 ms, faster than 88.04% of JavaScript online submissions for Two Sum II - Input array is sorted.
Memory Usage: 35.4 MB, less than 18.95% of JavaScript online submissions for Two Sum II - Input array is sorted.
Runtime: 76 ms, faster than 31.73% of JavaScript online submissions for Two Sum II - Input array is sorted.
Memory Usage: 35.2 MB, less than 38.09% of JavaScript online submissions for Two Sum II - Input array is sorted.