Conversation
akmhmgc
commented
Sep 28, 2025
| target以上であればleft以上、middle未満のインデックスの範囲に答えがあるかもしれないのでright = middleとして探索を続ける | ||
| target未満であればmiddle + 1以上、right未満のインデックスの範囲に答えがあるかもしれないのでleft = middle + 1として探索を続ける | ||
|
|
||
| rightは常に答えの候補になり得えて、探索の度に答えに近づくので探索が打ち切られた時のright(left)が答えになるはず。 |
Owner
Author
There was a problem hiding this comment.
理解が浅かった。
更新された時に言えることは、
- leftより左はtargetより小さい
- rightを含む右はtarget以上
なので探索が終わったタイミングでright == leftが答えになる。
akmhmgc
commented
Sep 28, 2025
| target以上であればleft以上、middle - 1以下のインデックスの範囲に答えがあるかもしれないのでright = middle - 1として探索を続ける | ||
| target未満であればmiddle + 1以上、right未満のインデックスの範囲に答えがあるかもしれないのでleft = middle + 1として探索を続ける | ||
|
|
||
| right + 1は常に答えの候補になり得えて、探索の度に答えに近づくので探索が打ち切られた時のright + 1が答えになるはず。 |
Owner
Author
There was a problem hiding this comment.
rightより右はtarget以上
leftより左はtargetより小さい
という条件になるので、探索が終了したタイミングでのright + 1が答えになる。
tokuhirat
reviewed
Sep 28, 2025
| end | ||
| end | ||
| right | ||
| end |
There was a problem hiding this comment.
一文字変数を使っているstep1のコードと比較して読みやすくなっていると感じました。
tokuhirat
reviewed
Sep 28, 2025
| つまり、target以上ではなく、targetより大きくてインデックスが最も小さくなるインデックスを返すことになる。 | ||
|
|
||
| ### 「right の初期値は nums.size - 1 でもいいですか。」 | ||
| right == leftが答えになるので、`nums.size`が答えになるパターンで間違った答えを返す。 |
There was a problem hiding this comment.
同じことかもしれませんが、right 以下に求めたいインデックスがあるような設定で書いているため初期値は nums.size でないといけない、というように思いました。
Owner
Author
There was a problem hiding this comment.
コメントありがとうございます!
具体例を考えないと反例を思いつかないというのが、まだ理解が浅い証拠かなと思い改めて整理してみました。
This file contains hidden or 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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
解いた問題
35. Search Insert Position
使用言語
Ruby
次に解く問題
153. Find Minimum in Rotated Sorted Array