要求:旋转数组的最小数字
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序数组的一个旋转,输出旋转数组的最小元素。例如,数组{3,4,5,1,2,}为{1,2,3,4,5}的一个旋转,该数组的最下值为0。
测试用例:
- 功能测试(输入的数组是升序排序数组的一个旋转,数组中有重复数字或者没有重复数字)
- 边界值测试(输入的数组是一个升序排序的数组,只包含一个数字的数组)
- 特殊输入测试(输入nullptr指针)
本题考点:
- 考查应聘者对二分查找的理解。本题变换了二分查找的条件,输入的数组不是排序的,而是排序数组的一个旋转。这要求我们对二分查找的过程有深刻的理解。
- 考查应聘者的沟通能力和学习能力。本题面试官提出了一个新的概念:数组的旋转。我们要在很短的时间内学习、理解这个新概念,在面试的过程中,可以主动和面试官沟通,把概念弄清楚。
- 考查应聘者思维的全面性。排序数组本身是数组旋转的一个特例。另外我们要考虑到数组中有相同数字的特例。如果不能很好地处理这些特例,就很难写出让面试官满意的完美代码。
源代码:
#include <exception>
using namespace std;
/********************************************************************
* 参数:
* number: 数组
* index1: 序号
* index2: 序号
*返回值:
* 最小值
********************************************************************/
int MinInOrder(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;
}
int Min(int *number, int length)
{
if (nullptr == number || length <= 0)
throw new exception("Invalid parameters");
int index1 = 0;
int index2 = length - 1;
int indexMid = index1;
while (number[index1] >= number[index2])
{
//如果index1和index指向相邻的两个数,
//则index1指向的哥递增子数组的最后一个数字,
//index2指向第二个子数组的第一个数字,也就是数组中的最小数字
if (index2 - index1 == 1)
{
indexMid = index2;
break;
}
indexMid = (index1 + index2) / 2;
//如果小标为index1、index2和indexMid指向的三个数字相同只能顺序查找
if (number[index1] == number[index2] && number[index1] == number[indexMid])
return MinInOrder(number, index1, index2);
//缩小查找范围
if (number[indexMid] >= number[index1])
index1 = indexMid;
else if (number[indexMid] <= number[index2])
index2 = indexMid;
}
return number[indexMid];
}
参考代码:https://github.com/zhedahht/CodingInterviewChinese2/tree/master/11_MinNumberInRotatedArray
自己代码:https://github.com/quinta2019/Offer/tree/master/11_Q_MinNumberInRotatedArray