33. Search in Rotated Sorted Array

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

Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length

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.


def search(nums, target):

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

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break