Conversation
| ```python | ||
| class Solution: | ||
| def searchInsert(self, nums: List[int], target: int) -> int: | ||
| left, right = 0, len(nums) - 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がテンプレートを覚えるのが一番良いといってくれたので、以下のテンプレートを覚えてみる。 |
There was a problem hiding this comment.
arahi10さんからおすすめされたのですが、アルゴリズムイントロダクションの該当セクションを読むのも手かもしれません
There was a problem hiding this comment.
実際におすすめさせていただいたこちらのスレッドが参考になるかもしれません。スレッドで引用してる別の方のプルリクエストのスレッドも参考になると思います。あまり固く考えず、たくさん読んでみてしっくりくるものを探してみては。(覚えゲーは無味ですし)
この問題に限らず、他の方のプルリクエストを見てみると直感的な理解の助けになると思います。思考の過程をトレースしてみたり、スレッドを参照して議論を追ってみたりすると良いんじゃないでしょうか。
Owner
Author
There was a problem hiding this comment.
お二人ともありがとうございます。不変式の考え方を初めて知ったのですが一番しっくり来ました。
今回の場合だと[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になるのだとなんとなく理解しました。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
直感的に理解するよりもテンプレートを覚える方が解きやすかったので覚えゲーでやっていく。