旋转数组的最小数字(三种解法)
题目
解题
方法一
两头比较 我最先想到的方法是设置两个指针low和high,low指向数组首部,high指向数组尾部,两个指针所指位置的数值进行比较,如果rotateArray[low]>=rotateArray[high],low++;反之high–。这种方法和第二种方法用时基本一致,而且不用单独考虑特殊值10111,上代码:
class Solution1 {
public:
int minNumberInRotateArray(vector<int> rotateArray) {
if(rotateArray.empty())
return 0;
int len = rotateArray.size();
if(len==0)
return 0;
if(len==1)
return rotateArray[0];
for(int i=0;i<len;i++)
{
if(rotateArray[i]<0)
return 0;
}
int low = 0,high = len-1;
int minNum = 0;
while(low<high && rotateArray[low]>=rotateArray[high])
{
low++;
}
minNum = rotateArray[low];
while(low<high && rotateArray[low]<rotateArray[high])
{
high--;
}
minNum = rotateArray[high];
int minNum1 = rotateArray[low];
return minNum;
}
};
方法二
剑指offer官方办法,二分查找变种 这个办法我感觉最麻烦的就是要考虑特殊值(比如:10111)情况,不然直接GG。代码如下:
class Solution {
public:
int minNumberInRotateArray(vector<int> rotateArray) {
int len = rotateArray.size();
if(len==0)
return 0;
for(int i=0;i<len;i++)
{
if(rotateArray[i]<0)
return 0;
}
int low = 0,high = len-1;
int mid;
while(low<high)
{
if(rotateArray[low]<rotateArray[high])
{
return rotateArray[low];
}else
{
mid = (low+high)/2;
if(rotateArray[mid]>rotateArray[high])
{
low = mid+1;
}else if(rotateArray[mid]<rotateArray[high])
{
high = mid;
}
else
{
low++;
}
}
}
return rotateArray[low];
}
};
方法三
暴力搜索 ,简直是万金油方法
最后放上main函数
int main()
{
vector<int> arr;
int num;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>num;
arr.push_back(num);
}
Solution s;
cout<<s.minNumberInRotateArray(arr)<<endl;
system("pause");
return 0;
}