zoukankan      html  css  js  c++  java
  • Leetcode-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.

    Analysis:

    For this problem, if we find that num[start]==num[mid]==num[end], we have to search both the left part and right part, because we do not know the min value is in which part. For example: 4 4 4 4 4 1 2 3 4 and 4 1 2 3 4 4 4 4 4.

    Solution:

     1 public class Solution {
     2     public int findMin(int[] num) {
     3         if (num.length==0) return -1;
     4         int start = 0, end = num.length-1;
     5         int min = findMinRecur(num,start,end);
     6         return min;
     7     }
     8     
     9     //NOTE: We need to consider the ending case that start==end, this happens when there is only one element in the array!
    10     public int findMinRecur(int[] num, int start, int end){
    11         if (start==end-1 || start==end){
    12             if (num[start]<num[end]) return num[start];
    13             else return num[end];
    14         }
    15         
    16         int mid = (start+end)/2;
    17         int min = Integer.MAX_VALUE;
    18         if (num[mid]<num[start]){
    19             min = findMinRecur(num,start,mid);
    20             return min;
    21         }
    22 
    23         if (num[mid]>num[end]){
    24             start = mid;
    25             min = findMinRecur(num,mid,end);
    26             return min;
    27         }
    28         
    29         if (num[mid]==num[start] && num[mid]==num[end]){
    30             int min1 = findMinRecur(num,start,mid);
    31             int min2 = findMinRecur(num,mid,end);
    32             if (min1<min2) return min1;
    33             else return min2;
    34         }
    35         
    36         if (num[start]>num[end]) return num[end];
    37         else return num[start];
    38     }
    39 }
  • 相关阅读:
    分析 ajax 请求并抓取 “今日头条的街拍图”
    requests + 正则表达式 获取 ‘猫眼电影top100’。
    爬虫基础(暂缓更新)
    Git 操作笔记:分布式版本控制系统
    python补充
    python基础
    8.最佳电影聚类分析
    文本分析 笔记
    7.文档聚类
    5.词项相似度分析
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4114637.html
Copyright © 2011-2022 走看看