所有代码均通过G++编译器测试,仅为练手纪录。
//面试题8:旋转数组中的最小数字
//题目:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
// 输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。
// 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
//面试题8:旋转数组中的最小数字
//题目:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
// 输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。
// 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
int FindMin(int *array,int nSize)
{
if(NULL == array || nSize <= 0)
{
return -1;
}
int nBegPos = 0;
int nEndPos = nSize-1;
int nMidPos = (nBegPos+nEndPos)/2;
if (array[nBegPos] < array[nEndPos])
{
//该递增序列未旋转
nMidPos = nBegPos;
}
else if (array[nBegPos] == array[nEndPos] && array[nBegPos] == array[nMidPos])
{
//该递增序列如{1,0,1,1,1}
while(++nBegPos != nEndPos)
{
if(array[nBegPos] < array[nBegPos-1])
{
break;
}
}
nMidPos = nBegPos ;
}
else
{
while (array[nBegPos] >= array[nEndPos])
{
if(1 == nEndPos-nBegPos)
{
nMidPos = nEndPos;
break;
}
nMidPos = (nBegPos+nEndPos)/2;
if (array[nMidPos] >= array[nBegPos])
{
nBegPos = nMidPos;
}
else if(array[nMidPos] <= array[nEndPos])
{
nEndPos = nMidPos;
}
}
}
return array[nMidPos];
}
void TestFindMin()
{
int arrValue1[] = {3,4,5,1,2};
int arrValue2[] = {1,0,1,1,1};
int arrValue3[] = {1,1,1,0,1};
int arrValue4[] = {1,1,1,1,1};
LogInfo("FindMin:%d",FindMin(arrValue1,sizeof(arrValue1)/sizeof(int)));
LogInfo("FindMin:%d",FindMin(arrValue2,sizeof(arrValue2)/sizeof(int)));
LogInfo("FindMin:%d",FindMin(arrValue3,sizeof(arrValue3)/sizeof(int)));
LogInfo("FindMin:%d",FindMin(arrValue4,sizeof(arrValue4)/sizeof(int)));
}
ZhaiPillary
2016-12-24