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.數組
有一個整數數組,返回其中兩個值之和爲指定值的索引。假設每一個輸入指定值只有一個解,而後不能使用同一個元素兩次code
Example:索引
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
思路:先想到的確定是兩次循環。遍歷數組每一個元素,獲target
與每一個元素的差值,而後利用數組的indexOf()
方法在剩餘的數組值中查找差值,若是有,則將當前索引與indexOf()
方法查找的索引保存在數組中,返回。ci
/** * @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
。。。第一版,總算完成了。element