# 兩和算法 twosome 基礎 非常重要 https://www.youtube.com/watch?v=Ivyh3V4QolA ``` var twoSum = function (nums, target){ const previousValues = {} for(let i=0; i<nums.length; i++){ const currentNumber =nums[i]; //抓取當前的數字 console.log(currentNumber); const neendedValue = target - currentNumber; // 目標 - 當前 為什麼用 - 因為它們會是互補 5 -1 = 4 跟 5-4 = 1 // a+b = c // c-a = b need // c-b = a need console.log(neendedValue); const index2 = previousValues[neendedValue]; // 這邊 就等於 a+b =c的總結了 因為 tager- current 就等於 c- a 了 // 這時候要找 b 但沒有 b就會 存起來 有對到的 就返回 // 第一次會找不到 第二次會 // [2] 找到第一次的 所以會跑去return // 1 = [2] // console.log(index2); if(index2 != null){ return [index2 , i] }else{ previousValues[currentNumber] = i //要將當前的數字 跟index存進去 // 所以會[currentNumber] = i //當前的 [2] = 1 //當前的 [7] = 2 } } } var b = twoSum([2,7,2,7],9) console.log(b); ``` previoustValue用object的原因 如果您使用數組而不是對象,那麼無論您作為對象的鍵存儲的 requiredValue 是什麼,例如 1000 都將是數組的索引。 這意味著您需要有一個在內存中至少佔據 1000 個點的數組。 通常,當您處理像這樣的大數字時,或者當數組中可能有許多空位置時,對象更適合 ## 內容解說 要找兩個和 所以要 a + b = c 但這樣要跑兩迴圈 抓住 a 跟 b 所以因該是 跑一個迴圈就好 沒有的存起來 所以第一個觀念應該是 跑a or b 那怎判斷呢 可以想 a + b = c 不就等於 c - a = b c - b = a 那要a 還是 b呢 不用想 因為不 - a 還是 -b 都一樣會出來 另外一個 所以你跑迴圈 把target 去檢調 當前的 如果 結果 有在我們存起來的裡面 就返回他 存起來的i 跟當前的 i 如果沒有的話呢 將當前的 存起來 key就 當前數字 value就是 當前的i ###### tags: `LeetCode`