Skip to content

35. Search Insert Position#5

Open
atmaxstar wants to merge 2 commits into
mainfrom
35
Open

35. Search Insert Position#5
atmaxstar wants to merge 2 commits into
mainfrom
35

Conversation

@atmaxstar
Copy link
Copy Markdown
Owner

@atmaxstar atmaxstar commented Apr 19, 2026

直感的に理解するよりもテンプレートを覚える方が解きやすかったので覚えゲーでやっていく。

```python
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums) - 1
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

無理に1行で書くと可読性を損なうような気がします

https://github.com/Yoshiki-Iwasa/Arai60/pull/35#discussion_r1699552857
left, rightに対してleftを閉区間、rightを開区間とすると初期地点はleft=0, right=len(nums)となる。もしbisect_leftを求めたいのなら最終地点は[False, False, [)True, True]こうなっていてleftのインデックスを返せば良い。そのためwhile文はleft < rightにしてleftがtargetの値を超えないようにnums[mid] < targetの際はleft=mid+1へ、nums[mid] >= targetの際はright=midとなる。bisect_rightの場合は[False, False, True, True,[)False]これが最終地点で、となるとnums[mid]<=targetの場合にleft=mid+1, それ以外の場合はright=midで更新すると求まる。

↑から数日経ってまた解いてみたのだが、やはりいちいち考えてみたものの普通にミスしてわからなくなった。Claudeがテンプレートを覚えるのが一番良いといってくれたので、以下のテンプレートを覚えてみる。
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

arahi10さんからおすすめされたのですが、アルゴリズムイントロダクションの該当セクションを読むのも手かもしれません

Copy link
Copy Markdown

@arahi10 arahi10 Apr 19, 2026

Choose a reason for hiding this comment

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

実際におすすめさせていただいたこちらのスレッドが参考になるかもしれません。スレッドで引用してる別の方のプルリクエストのスレッドも参考になると思います。あまり固く考えず、たくさん読んでみてしっくりくるものを探してみては。(覚えゲーは無味ですし)

この問題に限らず、他の方のプルリクエストを見てみると直感的な理解の助けになると思います。思考の過程をトレースしてみたり、スレッドを参照して議論を追ってみたりすると良いんじゃないでしょうか。

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.

お二人ともありがとうございます。不変式の考え方を初めて知ったのですが一番しっくり来ました。
今回の場合だと[left, right]の間に必ず答えがあるという条件を崩さずにleft, rightを更新していく必要があるのでnums[mid] < targetの場合はleft = mid + 1, elseの場合はright = midとなり、逆に704. Binary Searchのような問題だと[left, right]の間に答えがあるという条件が破られないためnums[mid] < targetの時left = mid + 1, nums[mid] > targetの時right = mid + 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