-
Notifications
You must be signed in to change notification settings - Fork 0
35. Search Insert Position #12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
|
|
||
| if nums[mid] == target: | ||
| return mid | ||
| elif nums[mid] > target: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
直前が return mid のため、ここは if にしてもよいと思います。
| - 探索区間は[`left`, `right`], [`left`, `right`)、(`left`, `right`]、(`left`, `right`) のどれか? | ||
| - 探索の終了条件を `left` と `right` が重なる時にするか?差分が1の時か? | ||
| - 幅のある書き方を読める方がより大事 | ||
| - > [false, false, false, ..., false, true, true, ture, ..., true] と並んだ配列があったとき、 false と true の境界の位置を求める問題とみなす。 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
少し前の自分の理解はこれでした。いまは、ここに挙げた分類の軸の他に、 left と right が値の位置を表す場合と、値と値の間の境界の位置を表す場合という分類もあると思っています。下のコードは、以下の 2 つの解釈ができます。
- left と right は値の位置を表している。区間には値が 1 個以上含まれている。区間には、 target 以上の最小の値が常に含まれている。 left は区間の左端の要素の位置を表している。 right は区間の右端の要素の 1 つ右の要素の位置を表している。
- left と right は値と値の境界の位置を表している。区間には境界が 1 個以上含まれている。境界が 1 個に定まったとき、境界の左側には target 未満の値のみが、境界の右側には target 以上の値のみがそれぞれ含まれる。 left は区間の左端の境界の位置を表している。 right は区間の右側の境界の位置を表している。
ソースコードとの整合性が取れるような解釈、読み方ができればよいと思います。
| if nums[mid] == target: | ||
| return index | ||
| if nums[mid] > target: | ||
| nums = nums[mid+1:] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
再帰だと (最適かはさておき) 更新されたリスト (スライス) を渡して再帰する範囲を狭めたりすると思うのですが、iterative で、しかも left, right インデックスを定義している状態でスライスを取る、というのは見ないように思います。
| * `left` > `right` となった場合、`target` が `nums` の要素に存在しない(最後まで探索した) | ||
| * `left` と `right` が重なる場合があるのに気を付ける |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
このあたりはそもそも left / right を何と定義しているかに依存するので、下の他の方の解答を見るプロセスで理解が深まっているといいなと思いました。たとえば left, right (両端を含む) なのか、left, right (right は含まない) なのか、などです。
|
|
||
| return left | ||
| ``` | ||
| `elif target <= nums[mid]:` は `else:` でも良いが、個人的にはこちらの方が `target` の値の境界条件が読みやすくて好み |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
同意です。というか、elif だけあると、処理されない場合 (else) があるのかな、という気持ちになります。
35. Search Insert Position
次回予告: 83. Remove Duplicates from Sorted List