Question
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
) 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 indexÂ3
 and becomeÂ[4,5,6,7,0,1,2]
.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
.You must write an algorithm withÂ
O(log n)
 runtime complexity.
This is abinary_search question.
Idea
- Use the regular binary search algorithm
- The trick here is to identify what portion of the array is sorted (where are we)
- If the left portion of the array is sorted, then M will be ≥ to L (we are in the left)
- Check to see where the target is is it in the right portion (is target < L or is target > M
- Otherwise it is in the left portion
- If the left portion of the array is not sorted then the right portion of the array is sorted (we are in the right)
- Check to see where the target is is it in the left portion (is target < M or is target > R
- Otherwise it is in the right portion
- If the left portion of the array is sorted, then M will be ≥ to L (we are in the left)
- If search fails return -1