Search in Rotated Sorted Array 在旋轉的陣列中查詢元素
阿新 • • 發佈:2019-01-25
class Solution {
public:
int search(int A[], int n, int target) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int low=0;
int high=n-1;
while(low<=high)
{
int middle=(low+high)/2;
if(target==A[middle]) return middle;
if(A[middle]>=A[low])
{
if(target>=A[low]&&target<A[middle])
{
high=middle-1;
}
else
{
low=middle+1;
}
}
else
{
if(target<=A[high]&&target>A[middle])
{
low=middle+1;
}
else
{
high=middle-1;
}
}
}
return -1;
}
};
public:
int search(int A[], int n, int target) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int low=0;
int high=n-1;
while(low<=high)
{
int middle=(low+high)/2;
if(target==A[middle]) return middle;
if(A[middle]>=A[low])
{
if(target>=A[low]&&target<A[middle])
{
high=middle-1;
}
else
{
low=middle+1;
}
}
else
{
if(target<=A[high]&&target>A[middle])
{
low=middle+1;
}
else
{
high=middle-1;
}
}
}
return -1;
}
};