Problem
Problem page: https://leetcode.com/problems/search-in-rotated-sorted-array/
Topics: Array, Binary Search
Difficulty: Hard
Similar problems: (M) Search in Rotated Sorted Array II, (M) Find Minimum in Rotated Sorted Array
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e.,
0 1 2 4 5 6 7might become4 5 6 7 0 1 2).You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Analysis
This is a variation on binary search. The array consists of two sorted subsequences. Every element in the left subsequence is greater than every element in the right one.
At each step, if A[left]<=A[right], the current segment lies within one sorted subsequence. Otherwise, it spans both sorted subsequences. Split the segment in two at mid and repeat the process recursively.
The problem says the array has no duplicates, because the algorithm can run into trouble with duplicates. For example, suppose the array is [4 5 6 7 0 3 4] and we're looking for 3. On the first step, the value at mid is 7, so we search the left segment. We won't find 3 there.
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-search-in-rotated-sorted-array/
