Skip to content

Conversation

@potrue
Copy link
Owner

@potrue potrue commented Aug 9, 2025

}
return left;
}
};

Choose a reason for hiding this comment

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

良いと思います。

while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) left = mid + 1;
if (nums[mid] >= target) right = mid;

Choose a reason for hiding this comment

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

ぶら下がりif文はメンテナンスしていった際に事故が起こりやすいという観点から、避けられるようです。
Hurukawa2121/leetcode#5 (comment)

あと、短い処理なのでelseで書いてもわかりやすい気がします。

https://github.com/takuya576/leetcode/pull/1/files
https://github.com/Ryotaro25/leetcode_first60/pull/45/files

いろいろなバリエーションで頭の中のシミュレーションを回してみようとすると難しい。。。
Copy link

@nodchip nodchip Aug 9, 2025

Choose a reason for hiding this comment

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

念のため確認させてください。今回の二分探索を書くとき、丸暗記したパターンを書き出しましたか?それとも、二分探索の仕組みを理解し、設定を考え、設定をもとにコードを書きましたか?

もし前者ですと、自分が使う道具を理解しようとしていないという、バッドシグナルだと思います。

試しに以下に答えてみてください。

  1. 区間には何が含まれますか?
  2. left が指す対象は何ですか?
  3. right が指す対象は何ですか?
  4. ループの不変条件 (left < right) を決めるとき、どのように決めましたか?
  5. int mid = (left + right) / 2; のほうがシンプルですが、なぜ int mid = left + (right - left) / 2; なのですか?
  6. left = mid + 1;+ 1 の部分は、なぜ + 1 なのですか? - 10 でないのはなぜですか?
  7. right = mid; にはなぜ - 1+ 1 を付けていないのですか?
  8. なぜ left を return しているのですか?

Copy link
Owner Author

@potrue potrue Aug 11, 2025

Choose a reason for hiding this comment

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

  1. 答えになりえるindexが含まれます。
  2. 答えになりえる最小のindex(境界を含む)のつもりでした。
  3. 答えになりえる最大のindex(境界を含む)のつもりでした。
  4. この問題は0 <= x <= nums.size()の中に必ず出すべき答えが存在する問題なので、答えの候補が複数あるうちはループを回し、一つに絞られた段階で抜けるというイメージでした。left != rightでもよかったかもしれません。
  5. int mid = (left + right) / 2;だと(left + right)を計算する段階でintのオーバーフローが発生する可能性があると思ったのでこのようにしました。
  6. nums[mid] < targetであるとき既にmidは答えにはなりえないので、+ 1を付けました。また、+ 1をつけないと、midを計算するときの/ 2の操作が切り捨てなので、leftrightも変化せずにループが回り続けることがあると思いました。(具体的には、right == left + 1であるような時を思い浮かべました。)
  7. nums[mid] >= targetであることはmidが答えになるケースを否定しない(nums[mid] == targetである可能性がある)ので、- 1をつけませんでした。
  8. ここにたどり着く時点ですでにleft == rightになっていると思うので、leftをreturnしてもrightをreturnしてもよいと思うのですが、一番簡潔だと思いleftをreturnしました。

Copy link

Choose a reason for hiding this comment

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

ありがとうございます。理想的な理解の仕方の一つをしていると思います。

@skypenguins
Copy link

読みやすいと思います。

Copy link

@ryosuketc ryosuketc left a comment

Choose a reason for hiding this comment

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

LGTM です!

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.

7 participants