Skip to content

Create 35. Search Insert Position.md#41

Open
tokuhirat wants to merge 1 commit intomainfrom
35.-Search-Insert-Position
Open

Create 35. Search Insert Position.md#41
tokuhirat wants to merge 1 commit intomainfrom
35.-Search-Insert-Position

Conversation

@tokuhirat
Copy link
Owner


- STEP1 では left = -1 である点と return right である点、が微妙に感じる引っかかるポイント。

- 以下は違うパターン。求める index が [left, right] に存在するように設定。初期値は自然に left = 0, right = len(nums) になる。left = right となったら終了。left 未満の index は target 未満、right 以上の index は target 以上となるようにする。nums[middle] < target の時は、middle で target 未満なので left はその右(+1)にする。right の位置では target 以上を保証しないといけないのでright = middleでなければいけない。右に狭める時は少なくとも +1 されるので狭まる。左に狭まる時は切り捨てなので狭まる。

Choose a reason for hiding this comment

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

自分もこちらのパターンの方が直観的で好みですね。

left = middle
else:
right = middle
return right

Choose a reason for hiding this comment

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

いいと思います。
leftは必ずtarget未満で、rightがtarget以上という不変条件を保ちながら更新し、最終的にleftとrightが隣り合って終了するのですね。

return left
```

- false と true の境界の位置を求めるというのはあまりイメージが湧かなかった。すぐ上のコードを半開区間らしいがあまりそうは感じない。区間の取り方をどのようにしても、ループ終了時に一つの要素(区間の区切り)を指していて欲しいという気持ちがあります。

Choose a reason for hiding this comment

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

すぐ上のコードを半開区間らしいがあまりそうは感じない。

right = len(nums) と範囲外に定義しているので、right が含まれない (半開区間) と想像されますね。

Copy link
Owner Author

Choose a reason for hiding this comment

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

コメントありがとうございます。
挿入する位置を探しているので right = len(nums) も解の候補としては範囲内と私は捉えている(以下A)のですがあまり主流ではなさそうです。Bはあまりしっくりきていないのですが、より適切な表現があれば教えていただきたいです。
A
[left, right] に挿入位置が含まれる。初期値は left = 0, right = len(nums)。left 未満、right より大きい index は解にならない(left 未満 の index では target より小さい、right 以上の index では target 以上か right = len(nums) である)。left = right になれば終了([left, right] には挿入位置が含まれ、候補が一つになったため)。
B
[left, right) について target との大小関係を調べる。初期値は left = 0, right = len(nums)。left 未満の index では target より小さい、right 以上の index では target 以上か right = len(nums) 。left = right になれば終了(探索すべき範囲が無くなったので left が求める解、left = len(nums) になりうる)。

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.

5 participants