Skip to content

Create 1.TwoSum.md#11

Open
hiroki-horiguchi-dev wants to merge 3 commits intomainfrom
hashmap-twoSum
Open

Create 1.TwoSum.md#11
hiroki-horiguchi-dev wants to merge 3 commits intomainfrom
hashmap-twoSum

Conversation

@hiroki-horiguchi-dev
Copy link
Owner

1.Two Sumを解きました、レビューお願いします。

@hiroki-horiguchi-dev hiroki-horiguchi-dev self-assigned this Mar 21, 2026
@hiroki-horiguchi-dev hiroki-horiguchi-dev changed the title Create 1_TwoSum.md Create 1.TwoSum.md Mar 21, 2026
int complement = target - nums[i];
complementToIndex.put(complement, i);
}
throw new IllegalArgumentException("numsに含まれる要素のペアで、和がtargetを満たすものは存在しない");
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

今回の例外ならエラーメッセージは英語で書くんじゃないかなぁと思います。文字化けの心配が少ないし、読める人が多いし。

日本語を扱うユーザに直接見せるエラーメッセージなら日本語を直接書くのも選択肢の一つではありますが、割とそれも弱めな選択肢かなぁ、と思います。エラーメッセージ自体は事前に定義しておいた英数字からなるIDなり通し番号をつけておいて、UIに表示させるときに対応する日本語のエラーメッセージに置き換える、みたいな実装をしても良いわけですし。


## 2nd
- 変数名を綺麗にする
- null を返していたが、Exception が適切だと判断した
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(LeetCodeがメソッドのシグニチャを決めてるので出来ませんが)例外を投げるよりかはOptional<int[]> を返り値の型にする方が好ましいと思います。解があるかどうかを呼び出し側がちゃんと検査するコードにすることを型システムでサポートできるので。

```java
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> complementToIndex = new HashMap<>();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

やや好みの問題ですが、「補数とそいつを補数とするような要素のインデックス」はちょっと自然言語で説明し辛にくく思います。説明の順番と意味上の主語が出る順番がぎゃくなので。その観点では自然言語で説明しやすく思える「要素の値とそのインデックス」の方が好ましいと思います(numToIndex とか)。

何で自然言語での説明のしやすさを優先したいかというと、説明しやすい処理ほど読み手が読みやすい(=理解するのにリソースを割かなくて済む)からですね

Copy link

@arahi10 arahi10 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

分かりやすかったと思います!
細かい点について、私見を述べました。

```java
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Map<Integer, Integer> map = new HashMap<>();

と、操作を行うための最小限のインターフェースで受けるコードをよく目にします。このあたりは、所属するチームの一般的な書き方に合わせることをおすすめします。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants