Skip to content

033-search-in-rotated-array#3

Open
05ryt31 wants to merge 1 commit intomainfrom
feat/33
Open

033-search-in-rotated-array#3
05ryt31 wants to merge 1 commit intomainfrom
feat/33

Conversation

@05ryt31
Copy link
Copy Markdown
Owner

@05ryt31 05ryt31 commented Dec 1, 2025

問題リンク

https://leetcode.com/problems/search-in-rotated-sorted-array/description/

問題文の概要

There is an integer array nums sorted in ascending order (with distinct values).

Prior to being passed to your function, nums is possibly left rotated at an unknown index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be left rotated by 3 indices and become [4,5,6,7,0,1,2].

Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

You must write an algorithm with O(log n) runtime complexity.

次に解く予定の問題

1011-capacity-to-ship-packages-within-D-days
https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/description/


## step2
Step1としては、
「左半分 or 右半分のどっちかは必ず昇順」
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

左半分も右半分もどちらも必ず照準に並んでいると思います。


if nums[mid] == target:
return mid
elif nums[mid] > nums[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.

他の個所が < または <= で統一されているにもかかわらず、ここだけ > なのが気になりました。 < に統一するとよいと思います。

if nums[mid] == target:
return mid
elif nums[mid] > nums[left]:
if nums[left] <= target < nums[mid]:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

念のため確認させてください。 nums[left] <= target < nums[mid] の代わりに nums[left] <= target  とした場合、どのような問題が起きますか?また、 target < nums[mid] とした場合、どのような問題が起きますか?

@@ -0,0 +1,24 @@
## 解答解説を見た後に自力で書いたコード

class Solution:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

仮に自分がこの問題を解くとしたら、 nums[left] <= target < nums[mid] の部分の条件を頭の中で整理するのが難しいと感じるため、この条件文を避けようと考えると思います。避けるにあたり、最小値の左側の境界を見つけたあと、 target が左半分にあるか、右半分にあるかを確認し、それらの中で再度二分探索をするという、 2 段階のコードを書くと思います。

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.

2 participants