Skip to content

Create 373. Find K Pairs with Smallest Sums.md#10

Open
hiroki-horiguchi-dev wants to merge 2 commits intomainfrom
heap-priorityqueue-373
Open

Create 373. Find K Pairs with Smallest Sums.md#10
hiroki-horiguchi-dev wants to merge 2 commits intomainfrom
heap-priorityqueue-373

Conversation

@hiroki-horiguchi-dev
Copy link
Owner

373. Find K Pairs with Smallest Sumsを解きました。
レビューお願いします。

@hiroki-horiguchi-dev hiroki-horiguchi-dev self-assigned this Mar 21, 2026
Copy link

@Shunii85 Shunii85 left a comment

Choose a reason for hiding this comment

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

レビューが遅くなってしまって申し訳ないです!

## 1st
- 30分
- nums1, nums2 の配列サイズ以上の k が与えられた時を0から考えつくのは初見は難しい気がする、これは答えみないとわからんよ。。
- 勘違いして解いてしまったけど備忘録として残しておく

Choose a reason for hiding this comment

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

これじゃ解けないのだろうか?と疑問に思ったのですが、smallestにすべて追加し終わっても取り出しが間に合っていないのだと思います。
つまり、最大k = nums1の長さの組み合わせまでしか出力できないのだと思います。LeetCodeで確認したところ、そうなっていました。


// ここが肝. i = 0, j = 0 が1周目のループで確定していて、i = 1 ~ i.length, j = 0 しか smallestQueue には入っていない
// 次の最小値のペアとして考えられるのは i = 0, j = 1 なので、これを smallestQueue 保存する
// 2周目以降がちょっと追いづらくて、poll() された要素の i, j + 1 を次の候補とするので、書き出したケースによっては意味不明な当たり方をしているように見えてしまい、最初の理解でつまづきがち

Choose a reason for hiding this comment

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

自分も理解があやふやな気がしたので、スライドを作ってみました。もしよければ見てみてください。
一行(もしくは一列)先に追加してしまう解き方のほうが理解しやすいですね。

https://docs.google.com/presentation/d/1MFDgwkFnZZaB_6b0P5HiHpvOS_WdOrfpZrQzrFaGOc0/edit?slide=id.p#slide=id.p

throw new IllegalArgumentException("サイズ1以上の配列を渡してください");
}
List<List<Integer>> result = new ArrayList<>();
PriorityQueue<int[]> indexPairQueue = new PriorityQueue<>((a, b) -> a[0] - b[0]);

Choose a reason for hiding this comment

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

少し長くなりますがSumAnd*でもいいかもしれません。

Choose a reason for hiding this comment

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

whileのなかではそんな感じにしていますね。

smallest.add(new int[]{num1 + num2, num1, num2});
}
int[] temp = smallest.poll();
List<Integer> pair = new ArrayList<>();
Copy link

Choose a reason for hiding this comment

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

List.of() を使うとシンプルに書けると思いました。
https://docs.oracle.com/javase/jp/9/docs/api/java/util/List.html#of-E-E-

result.add(List.of(temp[1], temp[2]));

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