10. 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 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.
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
Example 3:
Input: nums = [1], target = 0
Output: -1
Constraints:
1 <= nums.length <= 5000-104 <= nums[i] <= 104- All values of
numsare unique. numsis an ascending array that is possibly rotated.-104 <= target <= 104
Solution
Overview
Define the pivot index as representing the smallest element in nums.

In a rotated sorted array, the pivot value signifies where the rotation occurs. It partitions the array (of length n) into two sorted portions nums[0 ~ pivot - 1] and nums[pivot ~ n - 1].
Approach 1: Find Pivot Index + Binary Search
Intuition
If you are not familiar with binary search, please refer to our explore cards Binary Search Explore Card. We will focus on the usage in this article and not the underlying principles or implementation details.
To pinpoint the pivot value, we can employ a modified binary search algorithm and find the leftmost element that is smaller than or equal to the last element in nums.

After identifying the middle element in the searching space [left ~ right], we compare nums[mid] with nums[-1].
- If
nums[mid] > nums[-1], it suggests that the pivot value lies on the right ofnums[mid]. We will then proceed with the right half of the search space, which is[mid + 1 ~ right]. - Otherwise, the pivot value is
nums[mid]or it's situated to the left ofnums[mid], we continue with the left half of the searching space, which is[left ~ mid - 1].

By determining the pivot value, we set the boundaries for our subsequent binary searches. Once we have the pivot value, we can execute two binary searches on each half of the array to locate the target element.
Note: the typical way to calculate
midis(left + right) / 2. However, a safer way isleft + (right - left) / 2. The two equations are equivalent, but the second one is safer because it guarantees no number larger thanrightis ever stored. In the first equation, ifleft + rightis huge, then it could end up overflowing.
Algorithm
-
Perform a binary search to locate the pivot element by initializing the boundaries of the searching space as
left = 0