zoukankan      html  css  js  c++  java
  • 面试题8:旋转数组的最小数字

    //面试题8:旋转数组的最小数字
    //递增排序的{1,2,3,4,5}----->旋转为 {3,4,5,1,2}
    //求最小的数字
    package com.hb.jzoffer;
    
    import offer.utilities.ArrayUtils;
    
    //面试题8:旋转数组的最小数字
    
    //{1,2,3,4,5}----->旋转为 {3,4,5,1,2}
    publicclass MinNumberInRotatedArray_8 {
    public  int  Min(int[] array ) throws Exception{
            int  length = array.length ;
            if(length < 0){
                Exception e = new Exception();
                throw e;
            }
            int  index1 = 0 ; 
            int  index2 = length - 1;
            int  indexMid = index1 ; //如果下面while循环里面的不成立,说明数组是有序的,没有旋转,所以indexMid初始化为Index1
            while(array[index1] >= array[index2]){
                if(index2 - index1 == 1){
                    indexMid = index2;
                    break ;
                }
                indexMid = (index1 + index2) / 2 ;
                
                //如果下标为index1 、index2 和 indexMid 指向的三个数字相等,
                //则只能用书序查找
                if(array[index1] == array[index2] && array[indexMid] == array[index1]){
                    return MinInOrder(array , index1 , index2);                
                }
                
                if(array[indexMid] >= array[index1]){
                    index1 = indexMid ;
                }else if(array[indexMid] <= array[index2]){
                    index2 = indexMid ;
                }    
            }
            
            return array[indexMid];    
            
        }
        
        public int MinInOrder(int[] array , int index1 , int index2){
            int  result = array[index1];
            for(int i = index1 + 1 ; i <= index2 ; i++){
                if(result > array[i]){
                    result = array[i] ;
                }            
            }        
            return result;
        }
        
        public static void main(String[] args) throws Exception {
            int[] array = {3,4,5,1,2};
            int[] array1 = {1,1,1,0,1};
            MinNumberInRotatedArray_8 findMid = new MinNumberInRotatedArray_8();
            int min = findMid.Min(array);
            int min1 = findMid.Min(array1);
            ArrayUtils.printArray(array);
            System.out.println(min);
            ArrayUtils.printArray(array1);
            System.out.println(min1);
            
        }
        
        
    
    }
  • 相关阅读:
    JAVA 大数相加 POJ 1503
    Gao the Grid ZOJ 3647 数三角形
    为Layouts中的页面应用站点母版页的方法
    跨页面传值
    SharePoint Designer + InfoPath 无代码工作流设计实例
    自定义moss主题样式
    修改sharepoint文档库文件类型显示图标
    Workflow成功案例展示BingoSoft
    Walkthrough: 应用EventHandle开发的一个发邮件的小项目
    InfoPath + Workflow + MOSS
  • 原文地址:https://www.cnblogs.com/Mokaffe/p/4360937.html
Copyright © 2011-2022 走看看