two Sum
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].
第一版
思绪:先想到的肯定是两次轮回。遍历数组每一个元素,获target
与每一个元素的差值,然后应用数组的indexOf()
要领在盈余的数组值中查找差值,如果有,则将当前索引与indexOf()
要领查找的索引保留在数组中,返回。
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
var result = [];
for(var i=0; i<nums.length; i++) {
var tmp = target - nums[i];
var index = nums.indexOf(tmp, i+1);
if(index !== -1) {
result.push(i, index);
break;
}
}
if(result.length === 0) {
console.log('not found')
}
return result;
};
结论:耗时335ms,只要17%的
beats
。。。第一版,总算完成了。