题目
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
输入
[3,4,5,1,2]
输出
1
解析
使用二分法,还要考虑到特殊情况如0,1,1,1,1
c# 代码
class Program
{
static void Main(string[] args)
{
int[] a = { 3, 4, 5, 6, 7, 1, 2 };
int[] b = { 0, 1, 1, 1, 1 };
int[] c = { };
int[] d = { 1 };
int[] e = { 1, 2 };
Program.minNumberInRotateArray(e);
Console.Read();
}
public static int minNumberInRotateArray(int[] rotateArray)
{
if (rotateArray == null || rotateArray.Length == 0)
return 0;
int firstPoint = 0;
int lastPoint = rotateArray.Length - 1;
int minNumber=FindMinNumber(rotateArray, firstPoint, lastPoint);
return minNumber;
}
public static int FindMinNumber(int [] rotateArray,int firstPoint,int lastPoint)
{
int middlePoint = (firstPoint + lastPoint) / 2;
if (firstPoint == lastPoint)
return rotateArray[firstPoint];
if (middlePoint == firstPoint || middlePoint == lastPoint)
return (rotateArray[firstPoint] <= rotateArray[lastPoint]) ? rotateArray[firstPoint] : rotateArray[lastPoint];
if(rotateArray[lastPoint]<=rotateArray[middlePoint] && rotateArray[firstPoint]>=rotateArray[lastPoint])
return FindMinNumber(rotateArray, middlePoint, lastPoint);
if (rotateArray[middlePoint]<=rotateArray[lastPoint])
return FindMinNumber(rotateArray, firstPoint, middlePoint);
return 0;
}
}