(Daily algorithm) LeetCode --- Search in Rotated Sorted Array (Binary Search for rotating arrays)
Search in Rotated Sorted Array I & II
Leetcode
Perform binary search for ordered arrays (the following uses a non-decreasing array as an example ):
int binarySort(int A[], int lo, int hi, int target)
{
while(lo <= hi)
{
int mid = lo + (hi - lo)/2;
if(A[mid] == target)
return mid;
if(A[mid] < target)
lo = mid + 1;
else
hi = mid - 1;
}
}
Perform binary search for an ordered rotating array:
Eg. [7, 8, 9, 3, 4, 5, 6]
There is only one in the arrayBreakpoint
(The number is increased or decreased ).
The key to achieving this is to cleverly bypass this breakpoint.
1. If the first half is ordered:
target
In this rangehi = mid - 1
Not in this rangelo = mid + 1
2. If the first half is unordered
target
In the ordered interval of the second halflo = mid + 1
Not in this rangehi = mid - 1
That is to say, we give priority to the ordered part.
int search(int A[], int lo, int hi, int target)
{
while (lo <= hi)
{
int mid = (lo + hi) / 2;
if (A[mid] == target)
return mid;
if (A[lo] <= A[mid])
{
if (A[lo] <= target && target < A[mid])
hi = mid - 1;
else
lo = mid + 1;
} else {
if (A[mid] < target && target <= A[hi-1])
lo = mid + 1;
else
hi = mid - 1;
}
}
return -1;
}
Perform binary search for the rotated array containing repeated elements:
If repeated elements are allowed, if A [m]> = A [l] in the previous question, the assumption that [l, m] is an incremental sequence cannot be true, for example, [1, 3, 1, 1].
If A [m]> = A [l] is not necessarily incremental, split it into two conditions:
If A [m]> A [l], the interval [l, m] increases progressively.
If A [m] = A [l] cannot be determined, then l ++. Let's take A look at it.
bool search(int A[], int lo, int hi, int target)
{
while (lo <= hi)
{
int mid = (lo + hi) / 2;
if (A[mid] == target)
return true;
if (A[lo] < A[mid])
{
if (A[lo] <= target && target < A[mid])
hi = mid - 1;
else
lo = mid + 1;
} else if(A[lo] > A[mid]) {
if (A[mid] < target && target <= A[hi-1])
lo = mid + 1;
else
hi = mid - 1;
}
else
lo++;
}
return false;
}