Skip to content

Document algorithm for finding minimum in rotated array#14

Open
yakataN wants to merge 1 commit into
mainfrom
Find-Minimum-in-Rotated-Sorted-Array
Open

Document algorithm for finding minimum in rotated array#14
yakataN wants to merge 1 commit into
mainfrom
Find-Minimum-in-Rotated-Sorted-Array

Conversation

@yakataN
Copy link
Copy Markdown
Owner

@yakataN yakataN commented Sep 17, 2025

#### step2
https://github.com/KentaroJay/Leetcode/pull/18/files
https://github.com/Satorien/LeetCode/pull/42/files
- 半開区間じゃないコードを読み慣れていない。特に停止するかどうかが読み切れない。
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

https://discord.com/channels/1084280443945353267/1196498607977799853/1269532028819476562
リンク先の考え方で整理すると色々なパターンでも対応できるようになると思います。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Kaichi-Irie/leetcode-python#15 (comment)
この辺りも参考になると思います。

- また、変数targetが必要なくなる
- この場合左が開いている半開区間で考えているから、最初から単調増加の場合も考えるならばleft = -1にする必要がある。
- left_index -> left, right_index -> rightにしてもいいかもしれない。上から下に読むことを考えると、この変数はindexとしての振る舞いをしますというのが上の段階でわかるのは嬉しいかもしれないが、2行後にはその使い方をされているので。
- indexといいつつ、left_index = -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.

この違和感を解消するのであれば、左が閉じている区間で考えれば良いと思います。

```python
class Solution:
def findMin(self, nums: List[int]) -> int:
left, right = -1, 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.

好みの範囲と思いますが、個人的には二行で書いた方が見やすいと感じます。

right_index = len(nums) - 1
while right_index - left_index > 1:
mid_index = (left_index + right_index) // 2
if nums[mid_index] > target:
Copy link
Copy Markdown

@potrue potrue Sep 18, 2025

Choose a reason for hiding this comment

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

>=のほうが自然だと思います。(この条件に関してTrueになる要素とFalseになる要素が並んでいる配列だとnumsを捉えることができるので)
実際には、mid_indexが0になる頃にはwhileが回っていないので動作はすると思うのですが。

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]にして、nums[mid_index] > targetとするとif nums[0] < nums[-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.

4 participants