問題:
給一整數陣列與一個整數和,陣列中有兩個數字相加為其整數和,回傳兩個數字的位置,只有一組解
範例:
輸入: nums = [ 2, 7, 11, 15 ]
target = 9
輸出: [0,1]
提問:
陣列中數字是否重複? 回傳的陣列位置是否能重複?
一般想法:
迴圈跑兩次去相加所有數字。
進階解法:
跑一次迴圈同時也把值放到雜湊表裡,利用雜湊表能快速搜尋的特性,減少一次迴圈的時間。
雜湊表抓對應值是O(1)。
程式:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var twoSum = function (nums, target) { | |
let nums_map = new Map(); | |
for (let i = 0; i < nums.length; i++) { | |
let another = target - nums[i] | |
if (nums_map.has(another)) { | |
return [i, nums_map.get(another)] | |
} | |
nums_map.set(nums[i], i) | |
} | |
return null; | |
}; |
文章標籤
全站熱搜