Search in Rotated Sorted Array
Description
- 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 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 index3
to become[4,5,6,7,0,1,2]
. - Given the array
nums
after the possible rotation and an integertarget
, return the index oftarget
if it is innums
, or-1
if it is not innums
.
Constraints
1 <= nums.length <= 5000
-10^4 <= nums[i] <= 10^4
- All values of
nums
are unique. nums
is an ascending array that has been rotated between1
and5000
times.-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,
left
andright
, to the start and end of the array, respectively. - While
left
is less than or equal toright
, calculate the middle indexmid
. - If the element at
mid
is equal totarget
, returnmid
. - If the left half of the array is sorted, check if the
target
is in the sorted half. If it is, move theright
pointer tomid - 1
. Otherwise, move theleft
pointer tomid + 1
. - If the right half of the array is sorted, check if the
target
is in the sorted half. If it is, move theleft
pointer tomid + 1
. Otherwise, move theright
pointer tomid - 1
. - If the
target
is not found, return-1
.
Analysis
- Time Complexity:
O(log n)
- Space Complexity:
O(1)