Skip to content

Conversation

Satorien
Copy link
Owner

while left <= right:
middle = (left + right) // 2
if target <= nums[middle]:
right = middle - 1
Copy link

@potrue potrue Aug 13, 2025

Choose a reason for hiding this comment

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

right = middleのほうが個人的には良いと思いました。(target <= nums[middle]であってもmiddleが答えになりえるので)
これだと最後left == right + 1の状況になってleftが返されて終わりという感じになると思いますが、少しわかりにくいと感じました(捉え方によるのかもしれません)

```python
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
def binary_search(begin: int, end: int) -> int:
Copy link

Choose a reason for hiding this comment

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

関数名には、どのような値が返ってくるかを表す名前を付けたほうが、ソースコードが理解しやすくなると思います。

return left
```

- 開区間

Choose a reason for hiding this comment

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

個人的には、開区間か閉区間の選択ではなく、leftとrightがそれぞれ何を満たして欲しいものとして考えるかから始めることが重要な気がしています。

以下の方式であれば、
「rightは必ずtarget以上で、leftは必ずtarget未満である」というのが前提なので、停止するのはleftとrightが隣り合う時であり、targetが全要素より大きい/小さいを満たす初期値は〜、更新の仕方は〜と考えていくイメージです。

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.

4 participants