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
Divide problem into subproblems, solve each recursively, combine results. Classic examples: merge sort, quick sort, binary tree problems.
Implementation
def mergeSort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = mergeSort(arr[:mid])
right = mergeSort(arr[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
return result + left[i:] + right[j:]Complexity Analysis
Time Complexity
O(n log n)Space Complexity
O(n)Key Learning Points
Divide into subproblemsRecursive solutionCombine subresults
Related Problems to Practice
Merge SortQuick SortInvert Binary Tree
Complexity
Time:O(n log n)
Space:O(n)
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