题目:求旋转数组中的最小数字
以下为自己所写代码:
#include "stdafx.h"
#include <iostream>
#include <exception> using namespace std; int RotateArrayMin(int* array, int low, int high); int main(int argc, char* argv[])
{
const int length = ;
int array[length] = {,,,,,,,,,}; int Location = RotateArrayMin(array,,length-);
cout<<array[Location]<<endl; return ;
} //基本思想:采用折半查找的方法
// 改变搜索规则以及终止条件
//时间复杂度:O(logn)
int RotateArrayMin(int* array, int low, int high)
{
int SepValue = array[]; while(low < high)
{
int mid = (low + high)/;
if(array[mid] > SepValue)
low = mid + ;
else if(array[mid] < SepValue)
high = mid;
else
throw new std::exception("Values are not increasing!");
} if(low == high)
{
if(array[low] > SepValue)
return low+;
else
return low;
}
}
相比较于作者代码,自己弱爆了。。。
考虑问题很不全面。。。
要考虑的问题:
1、排序序列本身可视为特殊的旋转数组,即0旋转数组;
2、即使‘递增’,也要考虑数组中有相同数字的情形。
作者代码如下:
#include "stdafx.h"
#include<exception> int MinInOrder(int* numbers, int index1, int index2); int Min(int* numbers, int length)
{
if(numbers == NULL || length <= )
throw new std::exception("Invalid parameters"); int index1 = ;
int index2 = length - ;
int indexMid = index1;
while(numbers[index1] >= numbers[index2])
{
// 如果index1和index2指向相邻的两个数,
// 则index1指向第一个递增子数组的最后一个数字,
// index2指向第二个子数组的第一个数字,也就是数组中的最小数字
if(index2 - index1 == )
{
indexMid = index2;
break;
} // 如果下标index1、index2和indexMid指向的三个数字相等,
// 则只能顺序查找
indexMid = (index1 + index2) / ;
if(numbers[index1] == numbers[index2] && numbers[indexMid] == numbers[index1])
return MinInOrder(numbers, index1, index2); // 缩小查找范围
if(numbers[indexMid] >= numbers[index1])
index1 = indexMid;
else if(numbers[indexMid] <= numbers[index2])
index2 = indexMid;
} return numbers[indexMid];
} int MinInOrder(int* numbers, int index1, int index2)
{
int result = numbers[index1];
for(int i = index1 + ; i <= index2; ++i)
{
if(result > numbers[i])
result = numbers[i];
} return result;
}