Skip to content

solve: 33.Search in Rotated Sorted Array#43

Open
t9a-dev wants to merge 1 commit intomainfrom
33.Search-in-Rotated-Sorted-Array
Open

solve: 33.Search in Rotated Sorted Array#43
t9a-dev wants to merge 1 commit intomainfrom
33.Search-in-Rotated-Sorted-Array

Conversation

@t9a-dev
Copy link
Copy Markdown
Owner

@t9a-dev t9a-dev commented Dec 31, 2025

問題: 33. Search in Rotated Sorted Array
次に解く問題: 1011. Capacity To Ship Packages Within D Days
ファイルの構成: ./src/bin/<各ステップ>.rs

Copy link
Copy Markdown

@naoto-iwase naoto-iwase left a comment

Choose a reason for hiding this comment

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

全体的にとても読みやすかったです。

Comment thread src/bin/step1.rs
Comment on lines +56 to +58
if nums[middle] == target {
return middle as i32;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

step1はいわゆる探索範囲が閉区間[start, end]になっているタイプですが、ここのnums[middle] == targetの早期returnを外してstep2, 3のようにループ終了後に返り値を決める書き方に変えると、targetが配列numsの先頭にある場合などに、usize型のendで0 - 1を計算してオーバーフローする可能性がある、ということに注意が必要ですね。

Comment thread src/bin/step2a.rs
//(bool ,i32) -> (targetが左右どちらの区間に属するか, 探している値)
let target_key = (target <= *last, target);

match nums.binary_search_by_key(&target_key, |num| (num <= last, *num)) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

|num| (num <= last, *num) を target_key と合わせて二回書いている印象なので、一回変数においてはどうでしょうか。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます。以下のような感じにするとよりすっきり書けると理解しました。

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,
    }
}

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