[LeetCode][JavaScript]Two Sum
Two Sum
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
提示用map做,暴力O(n^2)也能解。
有个case比较狡猾,中招了。
1 /** 2 * @param {number[]} nums 3 * @param {number} target 4 * @return {number[]} 5 */ 6 var twoSum = function(nums, target) { 7 var map = {}; 8 for(var i in nums){ 9 if(map[nums[i]] !== undefined){ 10 return [parseInt(map[nums[i]]) + 1, parseInt(i) + 1]; 11 }else{ 12 map[target - nums[i]] = i; 13 } 14 } 15 }; 16 17 function test(){ 18 console.log(twoSum([3,4,-3,90], 0)); //13 19 console.log(twoSum([2,7,11,15], 9)); //12 20 console.log(twoSum([0,4,3,9], 9)); //14 21 console.log(twoSum([0,4,3,0], 0)); //14 22 console.log(twoSum([-3,4,3,90], 0)); //13 23 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。