旋转数组的最小数字
题目描述
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
思路
解法1:从头到尾遍历一次,当第一次遇到前面的值大于后面的值时,后面的值即为最小值,时间复杂度为
O(n)
解法2:根据旋转数组的特性,利用二分查找的思想
代码
解法1:
class Solution {
public:
int minNumberInRotateArray(vector<int> rotateArray) {
if(rotateArray.size() == 0)
return 0;
int res = 0;
int i;
for(i = 1; i < rotateArray.size(); i++){
if(rotateArray[i-1] > rotateArray[i]){
res = rotateArray[i];
break;
}
}
if(i==rotateArray.size())
res = rotateArray[0];
return res;
}
};
解法2:
class Solution {
public:
int MinInOrder(vector<int> rotateArray, int p1, int p2){//顺序查找
int res = rotateArray[p1];
for(int i = p1+1; i <= p2; i++){
res = res<rotateArray[i] ? res : rotateArray[i];
}
return res;
}
int minNumberInRotateArray(vector<int> rotateArray) {
int len = rotateArray.size();
int p1 = 0, p2 = len-1;
int pmid = p1;
int res = 0;
while(rotateArray[p1]>=rotateArray[p2]){
if(p2-p1 == 1){
pmid = p2;
break;
}
pmid = (p1 + p2) / 2;
//若p1,pmid,p2三个位置的元素相等,则无法判断最小值位于哪个区域,只能顺序查找
if(rotateArray[pmid] == rotateArray[p1] && rotateArray[p1] == rotateArray[p2])
return MinInOrder(rotateArray, p1, p2);
if(rotateArray[pmid] >= rotateArray[p1]){//最小值位于pmid和p2之间
p1 = pmid;
}else{//最小值位于p1和pmid之间
p2 = pmid;
}
}
return rotateArray[pmid];
}
};