问题
给定一个升序的整数数组A,让你在数组中找到任意下标x,使得A[x] == x。(数组下标从0开始)
例如:
[-1, 0, 1, 3, 10]中,x = 3即为所求。
解析:
最好想的思路就是遍历整个数组,
这样时间复杂度为O(N).
另一种解法
因为题目提示了是升序的整数数组A,那么就要想到能不能用二分查找的思想。
假设我们有一个数列B,其中B[0] > 0,那么易得,该数组中,必然不会出现所求的数字。
同理,如果B[n] < n,那么,在B[0...n]中,也不会有所求的数字。
因此我们可以在O(1)的时间内判断一个数组是否含有A[x] == x的数字。
然后采用二分的方法,所以能在O(logn)次内找到要找的数字。
代码:
#include<iostream>
using namespace std;
int searchNum(int *a,int n)
{
int low=0,high=n-1;
int m;
while(low<=high)
{
m=(low&high)+((low^high)>>1);
if(a[m]==m)
return m;
else
{
if(a[m]<m)
low=m+1;
else
high=m-1;
}
}
return -1;
}
int main()
{
int a[5]={-1,0,1,3,10};
int num=searchNum(a,5);
cout<<num<<endl;
return 0;
}