旋转数组的最小数字
2014-05-11 12:36
323 查看
本题来源于《剑指offer》66页面试题8:旋转数组的最小数字。
原题如下:
把一个数组最开始的肉感个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序数组的一个旋转,输出旋转数组的最小元素。
例如{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值 为1。
代码如下:
原题如下:
把一个数组最开始的肉感个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序数组的一个旋转,输出旋转数组的最小元素。
例如{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值 为1。
代码如下:
#include<iostream> using namespace std; int Min(int *number,int length); int MidInOrder(int *number,int index1,int index2); int Min(int *number,int length) { if(number==NULL||length<=0) { throw new std::exception("Invalid parameters!"); exit(0); } int index1=0,index2=length-1; int midIndex=index1; //index1初始化为数列最左侧,index2初始化为数列最右侧 //number[index2]肯定<=number[index1] //采用二分查找的思路,若number[index1]<=number[midIndex],则令index1=midIndex //若number[index2]>=numer[midIndex],则令index2=midIndex while(number[index1]>=number[index2]) { //若index2位于index1后一位,则表明此时index2的位置为最小值 if((index2-index1)==1) { midIndex=index2; break; } midIndex=(index1+index2)/2; //考虑到有些数组中存在相同的值,可能会出现index1、index2和midIndex处的值相同, //则此时应该在[index1,index2]区间内遍历查找 if(number[index1]==number[index2]&&number[index1]==number[midIndex]) return MidInOrder(number,index1,index2); if(number[midIndex]>=number[index1]) index1=midIndex; else if(number[midIndex]<=number[index2]) index2=midIndex; } return number[midIndex]; } //在[index1,index2]区间内遍历查找最小值 int MidInOrder(int *number,int index1,int index2) { int result=number[index1]; for(int i=index1+1;i<=index2;i++) { if(result>number[i]) result=number[i]; } return result; } //=============下面是测试代码================// void Test1() { int array1[5]={4,5,1,2,3}; int array2[5]={1,1,1,0,1}; cout<<"array1的最小值是:"<<Min(array1,5)<<endl; cout<<"array2的最小值是:"<<Min(array2,5)<<endl; } void Test2() { int array3[1]={1}; cout<<"array3的最小值是:"<<Min(array3,1)<<endl; } void Test3() { cout<<"NULL数组的最小值是:"<<Min(NULL,0)<<endl; } void main() { Test1(); Test2(); Test3(); }运行结果如下:
相关文章推荐
- 旋转数组的最小数字
- 剑指offer6 旋转数组的最小数字
- 【剑指offer】面试题8:旋转数组的最小数字
- [算法]找出旋转数组的最小数字
- 旋转数组的最小数字
- 题目11:旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组的最小数字
- [牛客网,剑指offer,python] 旋转数组的最小数字
- 剑指offer:旋转数组的最小数字 代码实现
- 旋转数组的最小数字
- 剑指offer__03__旋转数组的最小数字
- 剑指Offer 8 旋转数组的最小数字
- 旋转数组的最小数字
- 剑指offer-题8:旋转数组的最小数字
- 《剑指offer》旋转数组的最小数字
- 剑指Offer----旋转数组的最小数字
- 剑指offer系列-T8旋转数组的最小数字
- 九度oj 第3题 旋转数组的最小数字 何海涛:《剑指Offer:名企面试官精讲典型编程题》