问题描述:
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。
例如:
数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,最小值为1。
实现代码如下:
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> int findMinNumberInRotateArray(int array[],int left,int right); int searchMinNumberInArray(int array[],int mid,int right); int main(int argc, char *argv[]) { int rotateArray[]={ 1,0,1,1,1 }; printf("%d",findMinNumberInRotateArray(rotateArray,0,sizeof(rotateArray)/sizeof(int)-1)); printf("\nthe behind is test array which contains number value are equals:\n"); int rotateArrayHasEqualNum[]={ 1,1,1,2,2,3,3,3,40,2,2,2,2,3 }; printf("%d",findMinNumberInRotateArray(rotateArrayHasEqualNum,0,sizeof(rotateArrayHasEqualNum)/sizeof(int)-1)); return 0; } int findMinNumberInRotateArray(int array[],int left,int right){ int mid =(left+right)/2; if(right-left==1)return array[right]; if(array[left]==array[right] && array[mid]==array[right]){ printf("has some number's result:\n"); return searchMinNumberInArray(array,left,right); } if(array[left]<=array[mid]){ return findMinNumberInRotateArray(array,mid,right); }else{ return findMinNumberInRotateArray(array,left,mid); } } int searchMinNumberInArray(int array[],int left,int right){ int result = array[left],i; for(i=0;i<right;i++){ if(result>array[i]) return array[i]; } return result; }
而直接遍历的算法的时间复杂度是O(n)。
参考资料:
兼职offer
备注:
转载请注明出处:http://blog.csdn.net/wsyw126/article/details/51366915
作者:WSYW126