LeetCode 1. Two Sum

LeetCode 1. with javascript

*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

// 使用 map 快一點點 48ms

var twoSum = function(nums, target) {
 let map={}
 for(let i=0;i=0 不知為甚麼...否則run code會報undefined
   return([i,map[target-nums[i]]])
  }else{
   map[nums[i]]=i
     console.log(map)  
  }
    console.log(`==========================`)   
 }
};

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

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *