Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1].
解法思維
剛開始是想跑兩個迴圈,跑完再判斷相加是否等於目標值
1 2 3 4 5 6 7 8 9
var twoSum = function(nums, target) { for (let i = 0; i < nums.length; i++) { for (let j = 1; j < nums.length; j++) { if(nums[i]+nums[j]==target){ return [i,j] } } } };
別人的想法:跑迴圈,在判斷目標數值與迴圈數值相減,是否有在obj={}裡
1 2 3 4 5 6 7 8 9 10 11 12 13
var twoSum = function(nums, target) { //object for storing value and their index const obj = {}; const len = nums.length; for( let i=0; i< len; i++ ){ //if target - current value in array exist in obj then that's what we need if( target - nums[i] in obj ){ return [ obj[ target - nums[i] ], i ]; } //if target - current value doesn't exist in obj then push the value in obj obj[ nums[i] ] = i; } };