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.
你可以假设每个输入都只会有一种答案,同样的元素不能被重用。
例子:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
1 var twoSum = function(nums, target) { 2 var i, j, changeNum; 3 var len = nums.length; 4 for (i = 0; i < len - 1; i++) { 5 changeNum = target - nums[i]; 6 for (j = i + 1; j < len; j++) { 7 if (changeNum === nums[j]) { 8 return [i, j]; 9 } 10 } 11 } 12 };
本题唯一值得讲解的就是解题思路。
利用题目限定的唯一解,以及肯定有解。将目标值与数组每一项的差值在数组中进行遍历,从而找出答案。