把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
//主要思路:利用二分法进行查找,如果给出的数字中存在如{1,1,1,1,0,1}即前指针所指的值和后指针所指的值一
//样只能利用遍历查找
class Solution {
public:
int minNumberInRotateArray(vector<int> rotateArray) {
if(rotateArray.size() == 0)
{
return 0;
}
int first_ptr = 0;
int last_ptr = rotateArray.size() - 1;
int mid_ptr = first_ptr;
while(rotateArray[first_ptr] >= rotateArray[last_ptr])
{
if(last_ptr - first_ptr == 1)
{
mid_ptr = last_ptr;
break;
}
mid_ptr = (last_ptr + first_ptr)/2; //取中值
if(rotateArray[first_ptr] == rotateArray[last_ptr]
&& rotateArray[mid_ptr] == rotateArray[last_ptr]) //mid、first、last所指的值相等则利用循环查找最小值
{
return miniNum(rotateArray, first_ptr, last_ptr);
}
if(rotateArray[first_ptr] >= rotateArray[last_ptr]) //当first所指的值大于last所指的值将first置为mid
{
first_ptr = mid_ptr;
}
if(rotateArray[first_ptr] <= rotateArray[last_ptr]) //当first所指的值小于last所指的值将last置为mid
{
last_ptr = mid_ptr;
}
}
return rotateArray[mid_ptr];
}
int miniNum(vector<int> rotateArray, int first_ptr, int last_ptr) //查找最小数函数
{
int tmp = rotateArray[first_ptr];
for(int i = 0; i < last_ptr; i++)
{
if(rotateArray[i] < tmp)
{
tmp = rotateArray[i];
}
}
return tmp;
}
};