题目:把一个有序数组的末尾几位移到最开始的位置形成的新的新数组成为旋转数组,找出数组的最小值。
自己思路:
查找的话离不开遍历,二分,哈希,二叉搜索树。这题用遍历可以解决,但是太耗费时间了。旋转数组的特点:前面的有序序列必然大于后面的有序序列(假设数组之前是升序排列),可以根据二分进行查找。
代码:
二分查找的递归实现:
#include<iostream>
using namespace std;
int Binary(int temp[], int bin, int end){
int mid = (bin+end)/2;
if((end - bin) ==1){
return temp[end]>temp[bin]?temp[bin]:temp[end];
};
if(temp[mid]>temp[bin]){
Binary(temp, mid,end);
}
else{
Binary(temp, bin, mid);
};
};
int main(){
int a[5] = {3,4,5,1,2};
cout<<Binary(a, 0, 4) <<endl;
return 0;
};
二分查找的while循环实现:
#include<iostream>
using namespace std;
// int Binary(int temp[], int bin, int end){
// int mid = (bin+end)/2;
// if((end - bin) ==1){
// return temp[end]>temp[bin]?temp[bin]:temp[end];
// };
// if(temp[mid]>temp[bin]){
// Binary(temp, mid,end);
// }
// else{
// Binary(temp, bin, mid);
// };
// };
int Binary(int temp[], int bin, int end){
// int mid = (bin+end)/2;
int mid;
while(end-bin != 1){
mid = (bin+end)/2;
if(temp[mid]>temp[bin]){
bin = mid;
}else{
end = mid;
}
}
return temp[end];
}
int main(){
int a[5] = {3,4,5,1,2};
cout<<Binary(a, 0, 4) <<endl;
return 0;
};
代码优化,如果出现特殊情况应该怎么考虑
1、数组直接是有序的,旋转移动情况是0。
思路:判断数组的中间值是否大于第一个值并且小于最后一个值。加个if判断就可以了。
2、数组的值存在重复
思路:没办法,只能顺序查找。