leetcode:数组之Search in Rotated Sorted Array
给定一个有序数组,使其以某一个数为轴,将其之前的所有数都旋转到数组的末尾,例如:a=[0,1,2,4,5,6,7]选转后为a=[4,5,6,7,0,1,2];在旋转后的数组查找某一个元素。
二分查找法是要应用在有序的数组上,如果是无序的,那么二分查找就没有意义了,但旋转后的数组为一特例。
下面用二分查找法,来实现上述功能(假设数组中没有重复元素)
c++实现:
#include <iostream>
using namespace std;
int search(int a[],int n,int key)
{
int first=0,last=n;
while(first!=last)
{
int mid = (first+last)/2;
if(a[mid]==key)
return mid;
if(a[first]<=a[mid])
{
if(a[first]<=key && key<a[mid])
last=mid;
else
first=mid+1;
}
else{
if(a[mid]<key && key<=a[last-1])
first=mid+1;
else
last=mid;
}
}
return -1;
}
int main()
{
int a[7]={4,5,6,7,0,1,2};
int index=0;
index=search(a,7,0);
cout<<"下标索引:"<<index<<endl<<"查找的值:"<<a[index]<<endl;
return 0;
}
测试结果: