旋转数组的最小数字

题目:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。

思路:1.暴力遍历时间复杂度是O(N);

   2.采用二分查找法的时间复杂度是O(lgN);

int FindMinValue(int arrValue[], int length)
{
	if (arrValue == nullptr || length <= 0)
		throw new std::exception("Invalid parameters");

	int lowIndex = 0;
	int midIndex = 0;
	int highIndex = length - 1;
	if (arrValue[lowIndex] < arrValue[highIndex])
		return arrValue[lowIndex];

	while (lowIndex < highIndex)
	{
		midIndex = (highIndex - lowIndex) / 2 + lowIndex;
		if (arrValue[midIndex] > arrValue[lowIndex])
			lowIndex = midIndex;
		else if(arrValue[midIndex] < arrValue[lowIndex])
			highIndex = midIndex;
		else
		{
			if (arrValue[lowIndex] == arrValue[highIndex])
				highIndex--;
			else
				lowIndex = midIndex;
		}
		if (highIndex - lowIndex == 1)
			return arrValue[highIndex];
	}
	return arrValue[highIndex];
}

  

原文地址:https://www.cnblogs.com/yapp/p/9042775.html