zoukankan      html  css  js  c++  java
  • 剑指Offer(书):旋转数组的最小数字

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

    分析:因为有序,可以使用二分查找,但有特殊情况,比如{1,0,1,1,1}{1,1,1,0,1}都是{0,1,1,1,1}的旋转,使用二分查找时无法分辨0所在的位置是在前半段还是后半段,只能用顺序查找。

    public class Solution11 {
    
        /**
         * 使用二分查找,但有特殊情况,比如{1,0,1,1,1}{1,1,1,0,1}都是{0,1,1,1,1}的旋转,使用二分查找时无法分辨0所在的位置是在前半段还是后半段,只能用顺序查找。
         * {3,4,5,1,2}
         * @param array
         * @return
         */
        public int minNumberInRotateArray(int[] array) {
            if (array == null ) {
                throw new IllegalArgumentException("参数错误! array的值不能为null");
            }
            if(array.length == 0){
                return 0;
            }
            int left = 0;
            int right = array.length - 1;
            int mid = left;
            while (array[left] >= array[right]) {
                if (right - left == 1) {
                    mid = right;
                    break;
                }
                mid = (left + right) / 2;
                if (array[left] == array[right] && array[left] == array[mid]) {
                    int result = array[0];
                    for (int i = 0; i < array.length - 1; i++) {
                        if (array[i + 1] < array[i]) {
                            result = array[i + 1];
                        }
                    }
                    return result;
                }
                if (array[mid] >= array[left]) {
                    left = mid;
                } else if (array[mid] <= array[right]) {
                    right = mid;
                }
            }
            return array[mid];
        }
    
        public static void main(String[] args) {
            Solution11 solution11 = new Solution11();
            long start = System.nanoTime();
            System.out.println(solution11.minNumberInRotateArray(new int[]{1,2,3,4,5}));
            System.out.print((System.nanoTime() - start) / 1000000000.0);
        }
    }
  • 相关阅读:
    利用同步网盘搭建个人或团队SVN服务器
    Entity FrameWork Code First 之 MVC4 数据库初始化策略用法
    Entity FrameWork Code First 迁移命令详解
    Bootstrap Paginator分页插件+ajax
    Bootstrap的js分页插件属性介绍
    AtomicBoolean介绍与使用
    java线程:Atomic(原子)
    Java里的CompareAndSet(CAS)
    ThreadLocal详解
    CalendarUtil 日期操作工具类
  • 原文地址:https://www.cnblogs.com/liter7/p/9427163.html
Copyright © 2011-2022 走看看