Skip to content

35. Search Insert Position#39

Open
5103246 wants to merge 1 commit intomainfrom
35-search-insert-position
Open

35. Search Insert Position#39
5103246 wants to merge 1 commit intomainfrom
35-search-insert-position

Conversation

@5103246
Copy link
Copy Markdown
Owner

@5103246 5103246 commented Feb 14, 2026

Comment on lines +67 to +71
if (nums[middle] >= target) {
right = middle;
} else {
left = middle + 1;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

(完全に好みの範囲ですが)
個人的には、半開区間で書くと、leftとrightの更新式が非対称になりミスが増えそうな印象を受けました。

Comment on lines +103 to +112
while (left + 1 < right) {
int middle = left + (right - left) / 2;
if (nums[middle] >= target) {
right = middle;
} else {
left = middle;
}
}

return right;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

個人的には、この開区間のバージョンが一番しっくりきています。
left 自身とそれよりも左がNG, right 自身とそれよりも右がOKで、leftright が隣り合うまでループして、最後はOKの左端=right を返す、というのが分かりやすかったです。

- leftより左はtargetより小さく、rightを含めて右はtarget以上になるので、left == rightのとき、targetがあったらそこが答えになるし、targetがなくてもそこに挿入すればいい

- 上記の書き方で解いてみた
- geminiのstep1のコードレビューで、リストが空の場合は0を返すべき、middleがオーバーフローになると指摘されたのでそれを基に改善した
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

こういうのは決め次第なのですが、数式上の振る舞いが整っている方が後々都合がいいことが多いです。
sort(nums + [target]) したときの target のインデックスと思うと0が自然かなと思いますね。

- この説明は結構腑に落ちた。これをtrueの中で繰り返していくイメージかな
> まず最初に問題の設定についてですが、1. [false, false, ..., false, true, true, ..., true] の切れ目を探す。 2. [false, false, ..., false, true, true, ..., true] のうち一番初めの true を探す。
といった設定が多いと思います。
- 今回の問題は切れ目を探す問題か。
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Comment on lines +131 to +140
while (left <= right) {
int middle = left + (right - left) / 2;
if (nums[middle] >= target) {
right = middle - 1;
} else {
left = middle + 1;
}
}

return left;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

個人的にはこのパターンが理解に時間がかかりました。「leftright を追い越したときに left が答え」というのが腹落ちしにくかったです。

@mamo3gr
Copy link
Copy Markdown

mamo3gr commented Feb 17, 2026

コードには特に違和感ありませんでした。複数のパターンを試しているのも素晴らしいと思いました。

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