Search in Rotated Sorted Array
Description
- There is an integer array
numssorted in ascending order (with distinct values). - Prior to being passed to your function,
numsis possibly rotated at an unknown pivot indexk(1 <= k < nums.length) such that the resulting array is[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]](0-indexed). For example,[0,1,2,4,5,6,7]might be rotated at pivot index3to become[4,5,6,7,0,1,2]. - Given the array
numsafter the possible rotation and an integertarget, return the index oftargetif it is innums, or-1if it is not innums.
Constraints
1 <= nums.length <= 5000-10^4 <= nums[i] <= 10^4- All values of
numsare unique. numsis an ascending array that has been rotated between1and5000times.-10^4 <= target <= 10^4
Test Cases
-
Input:
nums = [4,5,6,7,0,1,2], target = 0
Output:4 -
Input:
nums = [4,5,6,7,0,1,2], target = 3
Output:-1
Code
Approach 1: Binary Search
Explanation
- Initialize two pointers,
leftandright, to the start and end of the array, respectively. - While
leftis less than or equal toright, calculate the middle indexmid. - If the element at
midis equal totarget, returnmid. - If the left half of the array is sorted, check if the
targetis in the sorted half. If it is, move therightpointer tomid - 1. Otherwise, move theleftpointer tomid + 1. - If the right half of the array is sorted, check if the
targetis in the sorted half. If it is, move theleftpointer tomid + 1. Otherwise, move therightpointer tomid - 1. - If the
targetis not found, return-1.
Analysis
- Time Complexity:
O(log n) - Space Complexity:
O(1)