剑指offer——6.旋转数组的最小数字

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/N1neDing/article/details/82120353

题目描述:

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

解题思路1:

从前向后遍历寻找,时间复杂度为O(n)。

参考源码1:

class Solution
{
public:
    int minNumberInRotateArray(vector<int> rotateArray)
    {
        if (rotateArray.size() == 0) return 0;
        for (int i = 0; i < rotateArray.size()-1; i++)
        {
            if (rotateArray[i] > rotateArray[i + 1])
            {
                return rotateArray[i + 1];
            }
        }
        return 0;
    }
};

解题思路2:

二分法,使用循环,时间复杂度为O(logn)。

参考源码2:

class Solution
{
public:
    int minNumberInRotateArray(vector<int> rotateArray)
    {
        if (rotateArray.size() == 0) return 0;
        int index1 = 0;
        int index2 = rotateArray.size() - 1;
        int indexmid = 0;
        while (rotateArray[index1] >= rotateArray[index2])
        {
            if (index2 - index1 == 1)
            {
                indexmid = index2;
                break;
            }
            indexmid = (index1 + index2) / 2;
            if (rotateArray[indexmid] >= rotateArray[index1])
            {
                index1 = indexmid;
            }
            else if (rotateArray[indexmid] <= rotateArray[index2])
            {
                index2 = indexmid;
            }
        }
        return rotateArray[indexmid];
    }
};

解题思路3:

采用二分法,具体实现使用递归,时间复杂度为O(logn)。

参考源码3:

class Solution
{
public:
    int index = 0;
    int minNumberInRotateArray(vector<int> rotateArray)
    {
        if (rotateArray.size() == 0) return 0;
        minNumberInRotateArrayHelper(rotateArray, 0, rotateArray.size() - 1);
        return rotateArray[index];
    }
    void minNumberInRotateArrayHelper(vector<int> rotateArray, int left, int right)
    {
        if (right - left == 1)
        {
            if (rotateArray[left] < rotateArray[right]) index = left;
            else
            {
                index = right;
            }
            return;
        }
        int mid = (right + left) / 2;
        if (rotateArray[mid] > rotateArray[right])
        {
            minNumberInRotateArrayHelper(rotateArray, mid, right);
        }
        else
        {
            minNumberInRotateArrayHelper(rotateArray, left, mid);
        }
    }
};

猜你喜欢

转载自blog.csdn.net/N1neDing/article/details/82120353
今日推荐