Skip to content

33. search_in_rotated_sorted_array#9

Merged
saagchicken merged 1 commit intomainfrom
saagchicken-patch-8
Mar 17, 2025
Merged

33. search_in_rotated_sorted_array#9
saagchicken merged 1 commit intomainfrom
saagchicken-patch-8

Conversation

@saagchicken
Copy link
Copy Markdown
Owner

No description provided.

用いた区間の種類に対し、範囲を狭めるためのロジックを、理由を理解したうえで、適切に記述できるか?
→midがtrueならright=mid, midがfalseならleft=mid+1

```python
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

このコードは何を考えて書いたかがとてもよく理解できてよいです。


def targetCanBeInThisInterval(left_closed, right_closed):
if nums[left_closed] <= nums[right_closed]:
return (nums[left_closed] <= target) & (target <= nums[right_closed])
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

& | は、ビット単位での and, or という意味です。論理的な方は and or を使うのが普通です。
また、() は優先順位を変えないときにはつけないことが多いです。
(誤りではないが、(2 * 3) + 4 とは書かないことが多いのと同じ。)

Python Operator Precedence を参照です。
https://docs.python.org/3/reference/expressions.html#operator-precedence

right = len(nums) - 1
while left < right:
if nums[left] <= nums[right]:
right = left
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

これは単に break でいいでしょう。

left = mid + 1
else:
right = mid
min = left
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

min は built-in function (組み込み関数)の中にあるので、できれば避けます。
https://docs.python.org/3/library/functions.html

(後の書き換えで built-in の min を使いたいときに混乱する、という程度の理由。)

Comment on lines +93 to +98
if min == 0:
left = 0
right = len(nums) - 1
elif target < nums[0]:
left = min
right = 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.

target <= nums[-1] と比較するとまとまりますかね。

回転の切れ目を見つけて、ソートされてる部分についてサーチする方法は賢いと思った。
しかし、たぶん二倍くらい遅いのかな?

この問題でbisectを使うには、keyをうまくクラフトする必要がありそう
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@saagchicken saagchicken merged commit 230c4ef into main Mar 17, 2025
→そのため、left=0, right=len(nums)-1から始める。

用いた区間の種類に対し、適切なループ不変条件を、理由を理解したうえで、設定できるか?
→閉区間なので、要素が一つだけになったときにそれが答えという考え方で行く。したがって、不変条件は、while left<right
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

私の場合、探索区間が閉区間ならば、探索区間が潰れるまでループを回すようにしていた(while left <= right)のですが、要素を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