zoukankan      html  css  js  c++  java
  • 《剑指Offer》算法题——“旋转数组”的最小数字

    题目描述

    把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个非递减序列的一个旋转,输出旋转数组的最小元素。例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
    //这里说的非递减并不是乱序的,也是递增的,只不过递增的过程中可以有相同数字而已
    #include <iostream>
    #include <vector>
    
    using namespace std;
    class Solution {
    public:
        int minNumberInRotateArray(vector<int> rotateArray) {
            int totallen = rotateArray.size();
            if (0 == totallen){
                return 0;
            }else if (1 == totallen){
                return rotateArray[0];
            }
            else{
                int vethead = 0;
                int vettail = totallen - 1;
                int vetlen = totallen;
                int vetmid = (vethead + vettail) / 2;
                while (rotateArray[vethead] >= rotateArray[vettail])//此时收缩范围
                {
                    if ((vettail - vethead) <= 1){//考虑过度收缩的情况,就需要往后遍历 比如{2,2,2,2,2,2,2,1,2},可能收缩到中间的两个2,而1此时在后边,所以需要向后遍历
                        if (rotateArray[vethead] == rotateArray[vettail] && rotateArray[vethead] >= rotateArray[vetmid]){
                            int i = vettail;
                            int j = vettail + 1;
                            while (rotateArray[i] <= rotateArray[j])
                            {
                                i++;
                                j++;
                            }
                            return rotateArray[j];
                        //return rotateArray[vettail];
                        }
    
                    
                    }
    
                    if (rotateArray[vethead] >= rotateArray[vetmid]){//向左收缩
                        vettail = vetmid;
                        vetmid = (vethead + vettail) / 2;
                        continue;
                    }
                    if (rotateArray[vethead] < rotateArray[vetmid]){//向右收缩
                        vethead = vetmid;
                        vetmid = (vethead + vettail) / 2;
                        continue;
                    }
                    
                }
                return rotateArray[vethead];
            }
            
        }
    };
    
    
    void main(){
        Solution s;
        //vector<int> va = { 10, 11, 12, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        vector<int> va = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 1, 2 };
        //vector<int> va = {2,2,1,2,2,2};
        //vector<int> va = { 1, 2, 2, 2, 2, 2 };
        int result = s.minNumberInRotateArray(va);
        cout << result << endl;
        system("pause");
    }

    这个算法有很多坑,需要考虑一些边界条件。不过最终还是通过了:

  • 相关阅读:
    使用maven创建web项目
    SSM框架——使用MyBatis Generator自动创建代码
    java中微信统一下单采坑(app微信支付)
    mac的safari浏览器调试h5
    服务端调用高德地图api实现ip定位城市
    mvn打包时,出现数据库连接错误
    其他知识点收集
    linux中项目占用cpu、内存过高时的排查经历
    linux中安装mysql
    linux中jdk的安装与配置
  • 原文地址:https://www.cnblogs.com/predator-wang/p/5354753.html
Copyright © 2011-2022 走看看