diff --git a/hash-map/two-sum/answer.md b/hash-map/two-sum/answer.md new file mode 100644 index 0000000..878f5af --- /dev/null +++ b/hash-map/two-sum/answer.md @@ -0,0 +1,221 @@ +# 1. Two Sum + +## STEP1 + +### 発想 + +* 全てのnumに対して、 + * pairがいるかをチェックし、いた場合には終了。 + * HashMapにnumを追加 + +* 最初、pairのチェックよりも、mapへの追加を先に行なってしまい、[3,3]のケースを考慮できておらず、エラーとなってしまった。 + +```javascript +const twoSum = function(nums, target) { + const num_to_index_table = new Map() + for (let i=0; i { + return { + value: num, + index: i, + } + }) + nums_with_index.sort((a, b) => a.value - b.value) + let left_idx = 0 + let right_idx = nums.length - 1 + while (left_idx < right_idx) { + const left = nums_with_index[left_idx] + const right = nums_with_index[right_idx] + if (left.value + right.value === target) { + return [left.index, right.index] + } + if (left.value + right.value < target) { + ++left_idx + continue + } + --right_idx + } + return new Error("pair is not found") +}; +``` + +* mapをもっと綺麗にかける。 + +* 変更前 + +```javascript + const nums_with_index = nums.map((num, i) => { + return { + value: num, + index: i, + } + }) +``` + +* 変更後 +```javascript + const nums_with_index = nums.map((value, index) => ({ value, index }) +``` + +## レビューを踏まえて + +### レビュー(1) エラーのハンドリングについて + +* 変更前 + +```javascript +const twoSum = function(nums, target) { + const num_to_index = new Map() + for (const idx_str in nums) { + const idx = Number(idx_str) + const num = nums[idx] + const twin_num = target - num + if (num_to_index.has(twin_num)) { + const twin_idx = num_to_index.get(twin_num) + return [idx, twin_idx] + } + num_to_index.set(num, idx) + } + return new Error("pair is not found") +}; +``` + +* 実行を中断したいのであれば、`return new Exception`ではなく、`throw new Exception`をすべきというコメントを受けた + +* 変更後 + +```javascript +const twoSum = function(nums, target) { + const num_to_index = new Map() + for (const idx_str in nums) { + const idx = Number(idx_str) + const num = nums[idx] + const twin_num = target - num + if (num_to_index.has(twin_num)) { + const twin_idx = num_to_index.get(twin_num) + return [idx, twin_idx] + } + num_to_index.set(num, idx) + } + // UPDATED + throw new Error("pair is not found") +}; +``` +