MediumLeetCode #33Binary Search
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. Given the array nums after rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.
Constraints
1 <= nums.length <= 5000, -10^4 <= nums[i] <= 10^4, All values of nums are unique
Examples
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Solution
Approach
Modified binary search. At each step, one half is always sorted. Check if target is in the sorted half, otherwise search the other half.
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[left] <= nums[mid]:
if nums[left] <= target < nums[mid]:
right = mid - 1
else:
left = mid + 1
else:
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1
return -1Complexity
Time:O(log n)
Space:O(1)
Hints
- 1.One half is always sorted after rotation
- 2.Determine which half is sorted
- 3.Check if target falls in sorted half
Asked at
Google