Open
Conversation
naoto-iwase
reviewed
Jan 1, 2026
Comment on lines
+56
to
+58
| if nums[middle] == target { | ||
| return middle as i32; | ||
| } |
There was a problem hiding this comment.
step1はいわゆる探索範囲が閉区間[start, end]になっているタイプですが、ここのnums[middle] == targetの早期returnを外してstep2, 3のようにループ終了後に返り値を決める書き方に変えると、targetが配列numsの先頭にある場合などに、usize型のendで0 - 1を計算してオーバーフローする可能性がある、ということに注意が必要ですね。
oda
reviewed
Jan 4, 2026
| //(bool ,i32) -> (targetが左右どちらの区間に属するか, 探している値) | ||
| let target_key = (target <= *last, target); | ||
|
|
||
| match nums.binary_search_by_key(&target_key, |num| (num <= last, *num)) { |
There was a problem hiding this comment.
|num| (num <= last, *num) を target_key と合わせて二回書いている印象なので、一回変数においてはどうでしょうか。
Owner
Author
There was a problem hiding this comment.
ありがとうございます。以下のような感じにするとよりすっきり書けると理解しました。
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
if nums.is_empty() {
return -1;
}
let last = *nums.last().unwrap();
let make_key = |x: i32| (x <= last, x);
match nums.binary_search_by_key(&make_key(target), |num| make_key(*num)) {
Ok(i) => i as i32,
Err(_) => -1,
}
}
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.
問題: 33. Search in Rotated Sorted Array
次に解く問題: 1011. Capacity To Ship Packages Within D Days
ファイルの構成:
./src/bin/<各ステップ>.rs