Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
解法一
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
if ( !Array.isArray(nums) || Object.prototype.toString.call(target) !== "[object Number]" ) {
return;
}
var i,j,len = nums.length;
for ( i = 0; i < len; i ++ ){
for ( j = i + 1; j < len; j ++ ){
if ( nums[i] + nums[j] === target )
return [i, j];
}
}
};
解法二
var twoSum = function(nums, target) {
if ( !Array.isArray(nums) || Object.prototype.toString.call(target) !== "[object Number]" )
return;
var arr = [],i,j,len = nums.length;
//构造哈希表
for ( i = 0; i < len; i ++ ){
arr[nums[i]] = i;
}
for ( i = 0; i < len; i ++ ){
j = arr[ target - nums[i] ];
// 例如 4+4=8,但只有一个4
if ( j !== undefined && i !== j ) return [ i, j ];
}
};
862

被折叠的 条评论
为什么被折叠?



