Open
Conversation
mamo3gr
reviewed
Mar 4, 2026
Comment on lines
+18
to
+20
| - leftより左側はtarget以上、rightを含む右側はtarget以上 | ||
| - middleの要素がtarget以上ならleftをmiddle+1に更新し、要素がtarget未満ならtargetを更新し、rightをmiddleにする。 | ||
| - left == rightがループの終了条件 |
There was a problem hiding this comment.
leftより左側はtarget以上、rightを含む右側はtarget以上
left == rightがループの終了条件
であれば、ループを抜けたとき nums[right] == min_target なので、ループ内で都度更新する手間が省けますね (step2).
mamo3gr
reviewed
Mar 4, 2026
Comment on lines
+88
to
+90
| - leftより左は最小値よりも大きく、rightを含む右側は最小値以上になる。なので探索終了時のleft, rightが最小値となる。 | ||
| - 最後尾の要素よりmiddleが大きい場合、middleを含む左側には最小値がないことがわかるのでleftをmiddle + 1にする。 | ||
| - middleが右端以下なら、昇順に並んでいることから、middleを含む左側に最小値があることがわかる。なので、rightをmiddleに更新する。 |
There was a problem hiding this comment.
[fyi]
自分は、left より左 とか、right を含む右側は、という含む・含まないの境界や、ループ終了条件と最終的にどこを返すのか、というのがなかなか頭の中で整理できないのですが、「nums.back()以下か?」のtrue,falseの境界を求めるのだと考えたら分かりやすかったです。
class Solution {
public:
int findMin(const vector<int>& nums) {
int ng = -1;
int ok = nums.size();
while (ng + 1 < ok) {
int middle = ng + (ok - ng) / 2;
if (nums[middle] <= nums.back()) {
ok = middle;
} else {
ng = middle;
}
}
return nums[ok];
}
};
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.
今回の問題
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
次の問題
https://leetcode.com/problems/search-in-rotated-sorted-array/