zoukankan      html  css  js  c++  java
  • [剑指offer] 旋转数组的最小数字

    题目描述

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

    第一想法是直接遍历查找旋转边界:

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

    但是实在太费时,最后还是用了二分查找查找边界:

    class Solution {
    public:
        int minNumberInRotateArray(vector<int> rotateArray) {
            if (rotateArray.size() == 0) return 0;
            int l = 0, r = rotateArray.size()- 2;
            int mid = (l + r) / 2;
            while (l <= r) {
                mid = (l + r) / 2;
                if (rotateArray[mid] > rotateArray[mid+1]) return rotateArray[mid+1];
                if (rotateArray[mid] > rotateArray[0]) l = mid + 1;
                else r = mid - 1;
            }
            return rotateArray[0];
        }
    };
  • 相关阅读:
    KVC
    MRC&ARC
    网络基础
    沙盒
    GCD深入了解
    iOS 架构模式MVVM
    iOS 源代码管理工具之SVN
    iOS给UIimage添加圆角的两种方式
    Objective-C 中,atomic原子性一定是安全的吗?
    iOS Block循环引用
  • 原文地址:https://www.cnblogs.com/zmj97/p/7895905.html
Copyright © 2011-2022 走看看