zoukankan      html  css  js  c++  java
  • Find Minimum in Rotated Sorted Array II

    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 a sorted array 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 public class Solution {
     2     public int findMin(int[] num) {
     3         if(num == null || num.length == 0) return 0;
     4         int min = Integer.MAX_VALUE;
     5         int str = 0, end = num.length - 1;
     6         while(str <= end){
     7             if(num[str] == num[end]){
     8                 int tmp = num[str];
     9                 min = min > tmp ? tmp : min;
    10                 while(str < end && num[str] == tmp) str ++;
    11                 while(str < end && num[end] == tmp) end --;
    12             }
    13             int mid = (str + end) / 2;
    14             min = min > num[mid] ? num[mid] : min;
    15             if(num[mid] < num[end]){
    16                 end = mid;
    17             }else if(num[mid] == num[end]){//from mid to end all the number is same
    18                 end = mid - 1;
    19             }else{
    20                 str = mid + 1;
    21             }
    22         }
    23         return min;
    24     }
    25 }
  • 相关阅读:
    Python 冒泡排序
    编程规范之注释篇
    编程规范之变量命名篇
    安装Django
    字典&列表的拓展理解
    小球落地
    Python结合sql登陆案例
    面向对象:两手交换牌
    每日一题(一)
    Web应用之LAMP源码环境部署
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/4044984.html
Copyright © 2011-2022 走看看