zoukankan      html  css  js  c++  java
  • 剑指Offer——旋转数组的最小数字

    1、题目描述

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

    2、代码实现

     1 package com.baozi.offer;
     2 
     3 /**
     4  * 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
     5  * 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。
     6  * 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
     7  * NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
     8  *
     9  * @author BaoZi
    10  * @create 2019-07-11-10:07
    11  */
    12 public class Offer6 {
    13     public static void main(String[] args) {
    14         int[] array = new int[]{3, 4, 5, 1, 2};
    15         Offer6 offer6 = new Offer6();
    16         int reslut = offer6.minNumberInRotateArray(array);
    17         System.out.println(reslut);
    18     }
    19 
    20     // 这里使用了二分查找的思想,查找效率肯定要比遍历查找的效率高的多。
    21     public int minNumberInRotateArray(int[] array) {
    22         //1、先判断数组为特殊情况的时候(检查边界值)
    23         if (array == null || array.length == 0) {
    24             return 0;
    25         }
    26         int first = 0;
    27         int last = array.length - 1;
    28         int indexMin = 0;
    29         //2、这里array[first] >= array[last]说明这个数组肯定经过旋转了
    30         //因为原数组是递增序列,如果没有旋转array[first] <=array[last]
    31         while (array[first] >= array[last]) {
    32             //3、指针first始终指向的是前边一个递增子数组序列,last始终指向的是第二个递增子数组序列
    33             //当last - first == 1说明first指向第一个序列的最后一个元素,last指向第二个序列的第一个元素
    34             //而且last指向的元素就是整个数组的最小元素
    35             if (last - first == 1) {
    36                 indexMin = last;
    37                 break;
    38             }
    39             indexMin = (first + last) / 2;
    40             //4、array[indexMin] >= array[first]说明indexMin指向的是第一个序列中的元素
    41             if (array[indexMin] >= array[first]) {
    42                 first = indexMin;
    43                 //5、array[indexMin] <= array[last]说明indexMin指向的是第二个序列中的元素
    44             } else if (array[indexMin] <= array[last]) {
    45                 last = indexMin;
    46             }
    47         }
    48         return array[indexMin];
    49     }
    50 }
  • 相关阅读:
    Leetcode Plus One
    Leetcode Swap Nodes in Pairs
    Leetcode Remove Nth Node From End of List
    leetcode Remove Duplicates from Sorted Array
    leetcode Remove Element
    leetcode Container With Most Water
    leetcode String to Integer (atoi)
    leetcode Palindrome Number
    leetcode Roman to Integer
    leetcode ZigZag Conversion
  • 原文地址:https://www.cnblogs.com/BaoZiY/p/11168350.html
Copyright © 2011-2022 走看看