当前位置:   article > 正文

剑指offer 面试题11 旋转数组的最小元素_旋转数组最少访问几个元素

旋转数组最少访问几个元素

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

利用两个index, 将复杂度降至O(logn), 注意考虑一种特殊情况要使用遍历查找

#include <iostream>
#include <string>
#include <memory>
#include <vector>
#include<stack>
#include<cmath>
#include<algorithm>
#include <iomanip>
using namespace std;

class Solution {
public:
    int minNumberInRotateArray(vector<int> rotateArray) {
        if(rotateArray.size()==0) {
            return 0;
        } else if(rotateArray.size()==1) {
            return rotateArray[0];
        }
        int index1=0,index2=rotateArray.size()-1;
        while(index1!=index2-1) {
            int mid=(index1+index2)/2;
            if(rotateArray[mid]==rotateArray[index1]&&rotateArray[index1]==rotateArray[index2]) {
                int min=rotateArray[0];
                for(int i=0;i<rotateArray.size();i++) {
                    if(rotateArray[i]<min) {
                        min=rotateArray[i];
                    }
                }
                return min;
            } else if(rotateArray[mid]>=rotateArray[index1]) {
                index1=mid;
            } else if(rotateArray[mid]<=rotateArray[index2]) {
                index2=mid;
            } 
        }
        return rotateArray[index2];
    }
};

int main()
{
    Solution sol;
    vector<int> test={3,4,5,1,1,2,3};
    int res=sol.minNumberInRotateArray(test);
    cout<<res<<endl;
    system("pause");
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/43602
推荐阅读
相关标签
  

闽ICP备14008679号