[剑指offer][06]旋转数组的最小数

2018-06-21  本文已影响0人  FloatingIsland
题目描述:

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

解题思路:

首尾不相等时,用二分查找。

首尾相等时,只能用顺序查找。

代码实现:
class Solution {
public:
    int minNumberInRotateArray(vector<int> rotateArray) {
        size_t low,high,mid;
        high=rotateArray.size();
        if(!high)
            return 0;
        high--;
        low=0;
        //首尾相等时暴力搜索
        if(rotateArray[low] == rotateArray[high]){
            for(int i=0;i<rotateArray.size()-1;i++){
                if(rotateArray[i+1]<rotateArray[i]){
                    return rotateArray[i+1];
                }
            }
        }
        //首尾不等时二分搜索
        while(low<high-1){
            mid=(low+high)/2;

            //如果中间数比末尾的数大
            if(rotateArray[mid]>rotateArray[high]){
                low=mid;
            }
            else{
                high=mid;
            }
        }
        return rotateArray[high];
    }
};

参考链接

剑指Offer面试题:7.旋转数组的最小数字

上一篇下一篇

猜你喜欢

热点阅读