标签:
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
https://leetcode.com/problems/two-sum/
提示用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 }
标签:
原文地址:http://www.cnblogs.com/Liok3187/p/4525249.html