[cpp]
class Solution {
//observation is the key, try to solve it by modifying binary search
public:
int search(int A[], int n, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int l = 0;
int r = n-1;
while (l <= r)
{
int mid = l+(r-l)/2;
if(A[mid] == target) return mid;
if (A[l] <= A[mid])//it is sorted in [l,mid], "=" contains an edge case:3, 1
{
if(A[mid] > target && A[l] <= target)
r = mid-1;
else
l = mid+1;
}
else//[mid,r] must be sorted, if [l,mid] not sorted
{
if(A[mid] < target && A[r] >= target)
l = mid+1;
else
r = mid-1;
}
}
return -1;
}
};
class Solution {
//observation is the key, try to solve it by modifying binary search
public:
int search(int A[], int n, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int l = 0;
int r = n-1;
while (l <= r)
{
int mid = l+(r-l)/2;
if(A[mid] == target) return mid;
if (A[l] <= A[mid])//it is sorted in [l,mid], "=" contains an edge case:3, 1
{
if(A[mid] > target && A[l] <= target)
r = mid-1;
else
l = mid+1;
}
else//[mid,r] must be sorted, if [l,mid] not sorted
{
if(A[mid] < target && A[r] >= target)
l = mid+1;
else
r = mid-1;
}
}
return -1;
}
};