题目:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增的排序的数组的一个旋转,输出旋转数组的最小元素。例如输入{1,2,3,4,5}的一个旋转为{3,4,5,1,2},该数组的最小值为1。
解析:旋转数组的特点:
(1)递增排序的数组旋转之后的数组可划分为两个排序的子数组;
(2)前面的子数组的元素都大于或等于后面子数组的元素;
(3)最小的元素刚好是两个子数组的分界线;
(4)旋转数组在一定程度上是有序的;
在有序的数组中可以用二分查找实现O(logn)的查找,我们也可用二分查找的思想寻找旋转数组的最小数字。
思路:
1. 设置两个指针,初始状态第一个指针指向前面子数组的第一个元素,第二个指针指向后面子数组的最后一个元素;
2. 找到两个指针的中间元素;
3.若其大于等于第一个指针指向的元素,则说明其在前面的子数组中,且显然最小元素在中间元素的右边,若其小于等于第二个指针指向的元素,则说明其在后面的子数组中,且显然最小元素在中间元素的左边。
如此,便可以缩小搜索范围,提高时间复杂度,最终第一个指针指向前面子数组的最后一个元素,而第二个指针指向后面子数组的第一个元素,它们处于相邻位置,而第二个指针指向的刚好是最小的元素。如下图:
注意:当两个指针指向的数字及它们中间的数字三者相等时,无法判断中间数字位于前面的子数组还是后面的子数组,也就无法移动两个指针来缩小查找的范围,此时只能用顺序查找的方法。如下图:
完整代码及其测试用例:
#include<iostream>
using namespace std;
int MinInOrder(int* numbers, int index1, int index2)
{
int result = numbers[index1];
for (int i = index1 + 1; i <= index2; i++)
{
if (result > numbers[i])
{
result = numbers[i];
}
}
return result;
}
int Min(int* numbers, int length)
{
if (numbers == NULL || length <= 0)
{
throw new std::exception("无效的参数!");
}
int index1 = 0;
int index2 = length - 1;
int indexMid = index1;
while (numbers[index1]>=numbers[index2])
{
// 如果index1和index2指向相邻的两个数,
// 则index1指向第一个递增子数组的最后一个数字,
// index2指向第二个子数组的第一个数字,也就是数组中的最小数字
if (index2 - index1 == 1)
{
indexMid = index2;
break;
}
// 如果下标为index1、index2和indexMid指向的三个数字相等,
// 则只能顺序查找
indexMid = (index1 + index2) / 2;
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];
}
// ====================测试代码====================
void Test(int* numbers, int length, int expected)
{
int result = 0;
try
{
result = Min(numbers, length);
for (int i = 0; i < length; ++i)
{
cout << numbers[i] << " ";
}
if (result == expected)
{
cout << " passed! " << endl;
}
else
{
cout << " failed! " << endl;
}
}
catch (...)
{
if (numbers == NULL)
{
cout << "Test passed." << endl;
}
else
{
cout << "Test failed." << endl;
}
}
}
int main()
{
// 典型输入,单调升序的数组的一个旋转
int array1[] = { 3, 4, 5, 1, 2 };
Test(array1, sizeof(array1) / sizeof(int), 1);
// 有重复数字,并且重复的数字刚好的最小的数字
int array2[] = { 3, 4, 5, 1, 1, 2 };
Test(array2, sizeof(array2) / sizeof(int), 1);
// 有重复数字,但重复的数字不是第一个数字和最后一个数字
int array3[] = { 3, 4, 5, 1, 2, 2 };
Test(array3, sizeof(array3) / sizeof(int), 1);
// 有重复的数字,并且重复的数字刚好是第一个数字和最后一个数字
int array4[] = { 1, 0, 1, 1, 1 };
Test(array4, sizeof(array4) / sizeof(int), 0);
// 单调升序数组,旋转0个元素,也就是单调升序数组本身
int array5[] = { 1, 2, 3, 4, 5 };
Test(array5, sizeof(array5) / sizeof(int), 1);
// 数组中只有一个数字
int array6[] = { 2 };
Test(array6, sizeof(array6) / sizeof(int), 2);
// 输入NULL
Test(NULL, 0, 0);
system("pause");
return 0;
}
运行结果:
3 4 5 1 2 passed!
3 4 5 1 1 2 passed!
3 4 5 1 2 2 passed!
1 0 1 1 1 passed!
1 2 3 4 5 passed!
2 passed!
Test passed.
请按任意键继续. . .