当前位置:   article > 正文

剑指offer面试题11:旋转数组的最小数字java实现_面试 java 实现 旋转数组的最小数字

面试 java 实现 旋转数组的最小数字

题目:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。

这里需要注意的是:

(1)把indexMid初始化为index1的原因:一旦发现数组中第一个数字小于最后一个数字,表明该数组是排序的,就可以直接返回第一个数字了。

(2)特殊情况的分析:如果下标为index1、index2和indexMid指向的三个数字相等,则只能顺序查找,因此这里定义了一个GetMinInOrder()方法。

public static int GetMin(int[] numbers)
    {
        if (numbers == null || numbers.Length <= 0)
        {
            return int.MinValue;
        }

        int index1 = 0;
        int index2 = numbers.Length - 1;
        // 把indexMid初始化为index1的原因:
        // 一旦发现数组中第一个数字小于最后一个数字,表明该数组是排序的
        // 就可以直接返回第一个数字了
        int indexMid = index1;

        while (numbers[index1] >= numbers[index2])
        {
            // 如果index1和index2指向相邻的两个数,
            // 则index1指向第一个递增子数组的最后一个数字,
            // index2指向第二个子数组的第一个数字,也就是数组中的最小数字
            if (index2 - index1 == 1)
            {
                indexMid = index2;
                break;
            }
            indexMid = (index1 + index2) / 2;
            // 特殊情况:如果下标为index1、index2和indexMid指向的三个数字相等,则只能顺序查找
            if (numbers[index1] == numbers[indexMid] && numbers[indexMid] == numbers[index2])
            {
                return GetMinInOrder(numbers, index1, index2);
            }
            // 缩小查找范围
            if (numbers[indexMid] >= numbers[index1])
            {
                index1 = indexMid;
            }
            else if (numbers[indexMid] <= numbers[index2])
            {
                index2 = indexMid;
            }
        }

        return numbers[indexMid];
    }

    public static int GetMinInOrder(int[] numbers, int index1, int index2)
    {
        int result = numbers[index1];
        for (int i = index1 + 1; i <= index2; ++i)  //注意在for循环条件处的++i和i++含义无本质区别,只是因为i++需要创建变量存储所以效率相比略低,故此场景下可优先使用++i
        {
            if (result > numbers[i])
            {
                result = numbers[i];
            }
        }

        return result;
    }
  • 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
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57

参考链接:https://www.cnblogs.com/edisonchou/p/4746561.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/43596
推荐阅读
相关标签
  

闽ICP备14008679号