Skip to content

33. Search in Rotated Sorted Array#2

Open
hayashi-ay wants to merge 1 commit intomainfrom
feat/33
Open

33. Search in Rotated Sorted Array#2
hayashi-ay wants to merge 1 commit intomainfrom
feat/33

Conversation

@hayashi-ay
Copy link
Copy Markdown
Owner

Comment on lines +42 to +45
ans = find_target(0, smallest_index - 1, target)
if ans != -1:
return ans
return find_target(smallest_index, len(nums) - 1, target)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

smallest_index が分かっているなら、targetがpivotの左右どちらかにあるか判断できると思います。

nums[smallest_index] <= target <= nums[-1] 

なら右側にありませんか?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます。たしかにそうです。
書き直してみました。

def search(self, nums: List[int], target: int) -> int:
    def find_target(left: int, right: int, target: int) -> int:
        while left <= right:
            mid = (left + right) // 2
            if nums[mid] == target:
                return mid
            elif nums[mid] > target:
                right = mid - 1
            else:
                left = mid + 1
        return -1

    left, right = 0, len(nums) - 1
    while left < right:
        mid = (left + right) // 2
        if nums[mid] > nums[-1]:
            left = mid + 1
        else:
            right = mid
    smallest_index = left
    if nums[smallest_index] <= target <= nums[-1]:
        return find_target(smallest_index, len(nums) - 1, target)
    else:
        return find_target(0, smallest_index, target)

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