Skip to content

Create 33. Search in Rotated Sorted Array.md#43

Open
tokuhirat wants to merge 1 commit intomainfrom
33.-Search-in-Rotated-Sorted-Array
Open

Create 33. Search in Rotated Sorted Array.md#43
tokuhirat wants to merge 1 commit intomainfrom
33.-Search-in-Rotated-Sorted-Array

Conversation

@tokuhirat
Copy link
Owner

else:
right = middle - 1
return -1
```

Choose a reason for hiding this comment

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

いいと思います。
が、個人的には回転位置を見つけたのちにソート済み配列(先頭から回転位置 or 回転位置から末尾)を探索する方針の方が理解しやすいかと思います

Copy link
Owner Author

Choose a reason for hiding this comment

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

コメントありがとうございます。書いてみました。わかりやすい方針だと思いました。

import bisect


class Solution:
    def search(self, nums: List[int], target: int) -> int:
        min_index = self._find_min_index(nums)
        if target > nums[-1]:
            i = bisect.bisect_left(nums[:min_index], target)
            if i < min_index and nums[i] == target:
                return i
        else:
            i = bisect.bisect_left(nums[min_index:], target) + min_index
            if i < len(nums) and nums[i] == target:
                return i
        return -1
        
    def _find_min_index(self, nums: List[int]) -> int:
        return bisect.bisect_left(nums, True, key=lambda x: x <= nums[-1])

Copy link

@ryosuketc ryosuketc left a comment

Choose a reason for hiding this comment

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

LGTM

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