题目要求:
二分查找被旋转的有序数组(不允许数组元素重复),返回待查找数的位置,如果不存在待查找数便返回-1。
例子:
(i.e., 0 1 2 4 5 6 7
被旋转后为 4 5 6 7 0 1 2
),查找0返回4。
代码:
#include<stdafx.h>
#include <iostream>
using namespace std;
class Solution {
public:
int searchInsert(int A[], int n, int target) {
int low=0;
int cur=(n-1)/2;
int high=n-1;
while(low<=high)
{
int cur= (low+high)/2;
if(target == A[cur])
return cur;
if(A[cur]<A[high])
{
if(target<=A[high] && target>A[cur])
low = cur+1;
else
high = cur-1;
}
else
{
if(target>=A[low] && target<A[cur])
high = cur-1;
else
low = cur+1;
}
}
return -1;
}
};
void main()
{
int A[7]={4,5,6,7,0,1,2};
Solution s;
cout<<s.searchInsert(A,7,0)<<endl;
getchar();
}