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 };
本題唯一值得講解的就是解題思路。
利用題目限定的唯一解,以及肯定有解。將目標值與數組每一項的差值在數組中進行遍歷,從而找出答案。