###### tags: `leetcode`, `javascript` # 【LeetCode】Javascript - #1 TwoSum --- ### 題目: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. --- ### 大概翻譯: 給一個裡面元素為int的陣列,陣列中會有兩個元素加起來等於target,回傳這兩個元素的位置。 --- 例如: ```javascript= Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. ``` --- 透過單純的雙迴圈,找`nums[i]+nums[j] == target` 就回傳 `[i,j]` ```javascript= var twoSum = function(nums, target) { for(i=0;i<nums.length-1;i++){ for(j=i+1;j<nums.length;j++){ if(nums[i]+nums[j] == target){ return [i,j] } } } }; ``` 但是效率看起來不太好啊,畢竟跑了兩層迴圈 ![](https://i.imgur.com/xYrckjY.png) --- 所以改寫成這樣,用一個物件把迴圈過程的值存起來 如果`target - nums[i]`在`obj`中找到值`x`,代表之前曾出現過值`x`,`target = x + nums[i]` 因此回傳`x`的位置與目前`nums[i]`的位置 ```javascript= var twoSum = function(nums, target) { var obj = {} for(i=0;i<nums.length;i++){ if(obj[target-nums[i]] >= 0){ return [obj[target-nums[i]],i] }else{ obj[nums[i]] = i } } }; ``` ![](https://i.imgur.com/0RRzVRG.png) 恩恩,效能似乎有比較好點,但也比較吃記憶體了:thinking_face: --- *新手工程師的筆記,純粹記錄學了些啥東西 如果有前輩高人讀了我的文,文中有任何錯誤再麻煩指教指教*