zoukankan      html  css  js  c++  java
  • leetcode 【 Find Minimum in Rotated Sorted Array II 】python 实现

    题目

    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.

    代码:oj测试通过 Runtime: 82 ms

     1 class Solution:
     2     # @param num, a list of integer
     3     # @return an integer
     4     def findMin(self, num):
     5         # none case
     6         if num is None :
     7             return None
     8         # only one element case
     9         if len(num)==1 :
    10             return num[0]
    11         # binary search case
    12         start = 0
    13         end = len(num)-1
    14         while start<end and num[start]>=num[end]:
    15             mid = (start+end)/2
    16             if num[start]>num[end]:
    17                 if num[mid]>num[end] :
    18                     start = mid+1
    19                 else:
    20                     end = mid
    21             else:
    22                 if num[mid]>num[end] :
    23                     start = mid+1
    24                 else :
    25                     start = start+1
    26         return num[start]

    思路

    对比之前一道题:http://www.cnblogs.com/xbf9xbf/p/4261334.html

    这道题需要考虑duplicate的case。

    简略地说,跟之前不带duplicate的case相比,核心的区别在:

    不带duplicate的case : num[start]>num[end]是铁定成立的

    带duplicate的case : num[start]>num[end]不一定是成立的,还可能是num[start]==num[end]

    就是多了这么一个等号的可能,所以最直观的办法就是单独把这种等号的情况拿出来嘛。

    因此需要讨论的情况一共有两种:

    1. num[start]>num[end]

    2. num[start]==num[end]

    有人可能要问,为啥不能有num[start]<num[end]的情况?答:因为在while循环终止条件中已经限定了num[start]>=num[end];如果真有num[start]<num[end]的情况,那么当前start到end位置的数组已经是有序的了,直接return[start]就OK了。

    Tips:

    在AC之前还遇上几个问题:

    1. 如果出现无法判断最小值是在左半边还是右半边的时候,不要同时start=start+1 end=end-1,start=start+1即可,否则会指针溢出

    2. 之前在while循环条件的时候,一直写的是start<=end。就是多了这么一个等号,submit了几次一直不能AC。究其原因,如果start==end,就会导致执行start=start+1语句,不是溢出就是错。如果修改一下while循环的条件,start<end,那么当start==end的时候自动就退出循环了,并且返回num[start]了。

  • 相关阅读:
    hdu6229 Wandering Robots 2017沈阳区域赛M题 思维加map
    hdu6223 Infinite Fraction Path 2017沈阳区域赛G题 bfs加剪枝(好题)
    hdu6438 Buy and Resell 买卖物品 ccpc网络赛 贪心
    hdu6441 Find Integer 求勾股数 费马大定理
    bzoj 1176 Mokia
    luogu 3415 祭坛
    bzoj 1010 玩具装箱
    bzoj 3312 No Change
    luogu 3383【模板】线性筛素数
    bzoj 1067 降雨量
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4264106.html
Copyright © 2011-2022 走看看