剑指offer(6)-旋转数组的最小数字

题目描述


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

题目解析


这道题最直观的解法并不难,从头到尾遍历数组一次,我们就能找出最小的元素。这种思路的时间复杂度显然是O(n)。但是这个思路没有利用输入的旋转数组的特性,肯定达不到面试官的要求。

我们注意到旋转之后的数组实际上可以划分为两个排序的子数组,而且前面的子数组的元素都大于或者等于后面子数组的元素。我们还注意到最小的元素刚好是这两个子数组的分界线。在排序的数组中我们可以用二分查找法实现O(logn)的查找。本题给出的数组在一定程度上是排序的,因此我们可以试着用二分查找法的思路老寻找这个最小的元素。

代码


class Solution {
public:
    int minNumberInRotateArray(vector<int> rotateArray) {
        if (rotateArray.size() == 0) {
            return 0;
        }
        long startIndex = 0;
        long endIndex = rotateArray.size() - 1;
        long indexMid = startIndex ;
        while (rotateArray[startIndex] >= rotateArray[endIndex]) {
            if (endIndex - startIndex == 1) {
                indexMid = endIndex;
                break;
            }
            indexMid = (startIndex + endIndex)/2;
            if (rotateArray[startIndex] == rotateArray[endIndex] && rotateArray[startIndex] == rotateArray[indexMid]) {
                return MinInOrder(rotateArray);
            }
            if (rotateArray[indexMid] >= rotateArray[startIndex]) {
                startIndex = indexMid;
            }else if (rotateArray[indexMid] <= rotateArray[startIndex]){
                endIndex = indexMid;
            }
        }
        return rotateArray[indexMid];
    }
private:     
     int MinInOrder(vector<int> rotateArray){
        int result = rotateArray[0];
        for (int i = 0; i < rotateArray.size(); i++) {
            if (result > rotateArray[i]) {
                result = rotateArray[i];
            }
        }
        return result;
    }

};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值