Leetcode # 33 (Python): Search in Rotated Sorted Array

정욱·2021년 4월 27일
0

Leetcode

목록 보기
34/38
post-custom-banner

Search in Rotated Sorted Array

  • Difficulty: Medium
  • Type: Binary Search
  • link

Porblem

Solution

  • Find pivot (index of the minimum value)
  • Perform binary search with pivot added to the mid point
  • Time Complexity: O(log n)
class Solution:
    def search(self, nums: List[int], target: int) -> int:
        if not nums:
            return -1

        # Find min
        left, right = 0, len(nums) - 1
        while left < right:
            mid = left + (right - left) // 2

            if nums[mid] > nums[right]:
                left = mid + 1
            else:
                right = mid

        pivot = left

        # Binary search relative to pivot
        left, right = 0, len(nums) - 1
        while left <= right:
            mid = left + (right - left) // 2
            mid_pivot = (mid + pivot) % len(nums)

            if nums[mid_pivot] < target:
                left = mid + 1
            elif nums[mid_pivot] > target:
                right = mid - 1
            else:
                return mid_pivot
        return -1
post-custom-banner

1개의 댓글

comment-user-thumbnail
2021년 12월 18일

I found that solution is very popular and helpful : https://www.youtube.com/watch?v=Z76IRo_vV0s

답글 달기