zoukankan      html  css  js  c++  java
  • 154. Find Minimum in Rotated Sorted Array II(剑指offer)



    Follow up for "Find Minimum in Rotated Sorted Array":
    What if duplicates are allowed?

    Would this affect the run-time complexity? How and why?

    Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

    (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

    Find the minimum element.

    The array may contain duplicates.

     1 class Solution {
     2     public int findMin(int[] a) {
     3            if(a.length==0) return 0 ;
     4         int left = 0,right = a.length-1,mid=0;
     5         while(a[left]>=a[right]){
     6             if(right-left==1) return a[right];
     7             
     8             mid = left +(right-left)/2;
     9            // 特殊处理[1 1 1 0 1]
    10             // code
    11             if((a[mid]==a[right])&&(a[mid]==a[left]))
    12                 return find_min(a,left,right);
    13             //
    14             if(a[left]<=a[mid]) left =mid;
    15             if(a[right]>=a[mid])right = mid;
    16         }
    17         return a[mid];
    18     }
    19     private int find_min(int[] a,int left,int right){
    20         int min = a[left];
    21         for(int i =left;i<=right;i++)
    22             if(a[i]<min) 
    23                 min =a[i];
    24         return min;
    25     }
    26 }
  • 相关阅读:
    JPA常见坑
    IDEA的快捷键使用
    java注解
    @ResponseBody注解之返回json
    mybatis坑之Integer值为null
    Java后端之SQL语句
    SSM项目配置swaggerUI
    mybatis入门案例2
    mybatis入门案例
    部署本地服务器的前端及后端
  • 原文地址:https://www.cnblogs.com/zle1992/p/8836579.html
Copyright © 2011-2022 走看看