33.
Search in Rotated Sorted Array
Medium
Problem Description
There is an integer array nums sorted in ascending order (with distinct values).
Examples
Input: [4,5,6,7,0,1,2], 0
Output: 4
Input: [4,5,6,7,0,1,2], 3
Output: -1
Input: [1], 0
Output: -1
Constraints
1 <= nums.length <= 5000
-10^4 <= nums[i] <= 10^4
All values of nums are unique.
-10^4 <= target <= 10^4
Approach to Solve
Use a two-pointer approach to find the target.
Code Implementation
class Solution:
def search(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
if nums[left] <= nums[mid]:
if nums[left] <= target < nums[mid]:
right = mid - 1
else:
left = mid + 1
else:
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1
return -1
Explanation
This solution uses a two-pointer approach to find the target. Here's a detailed explanation of the algorithm:
- Initialize left and right pointers to the start and end of the array, respectively.
- While left is less than or equal to right:
- Calculate the middle index mid.
- If nums[mid] is equal to the target, return mid.
- If nums[mid] is less than the target, move the left pointer to mid + 1.
- Otherwise, move the right pointer to mid - 1.
- If the target is not found, return -1.
Complexity
- Time Complexity: O(log n)
- Space Complexity: O(1)
Code copied to clipboard!