LeetCode 1. Two Sum

*javascript solution

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].
 ===========
leetcode第一題,首先想到的自然是超暴力的雙迴圈...

// 暴力法 => 兩個迴圈 => 52ms

var twoSum = function(nums, target) {
 let i
 let j
 for(i=0;i<nums.length;i++){
  for(j=i+1;j<nums.length;j++){
   if(nums[i]+nums[j]==target)
    return [i,j]
  }
 }
};

// 使用 map 快一點點 48ms

var twoSum = function(nums, target) {
 let map={}
 for(let i=0;i<nums.length;i++){
    console.log(`i= ${i},nums[i]= ${nums[i]}, target-nums[i] =${target-nums[i]}, 
                 map[target-nums[i]] = map[${target-nums[i]}] = ${map[target-nums[i]]}, 
                 map[nums[i]] = map[${nums[i]}] = ${map[nums[i]]} map=`) 
  if(map[target-nums[i]]>=0){
  // 必須寫>=0 不知為甚麼...否則run code會報undefined
   return([i,map[target-nums[i]]])
  }else{
   map[nums[i]]=i
     console.log(map)  
  }
    console.log(`==========================`)   
 }
};

大致理解但其實說穿了還是不太理解,把東西都印出來會比較好懂一點...QAQ