zoukankan      html  css  js  c++  java
  • Leetcode** 154. Find Minimum in Rotated Sorted Array II

    Description: Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,4,4,5,6,7] might become:

    • [4,5,6,7,0,1,4] if it was rotated 4 times.
    • [0,1,4,4,5,6,7] if it was rotated 7 times.

    Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].

    Given the sorted rotated array nums that may contain duplicates, return the minimum element of this array.

    Link: 154. Find Minimum in Rotated Sorted Array II

    Examples:

    Example 1:
    Input: nums = [1,3,5]
    Output: 1
    
    Example 2:
    Input: nums = [2,2,2,0,1]
    Output: 0
    
    Example 3:
    Input: nums = [1,3,3]
    Output: 1
    
    Example 4:
    Input: nums = [3,1,3,3]
    Output: 1

    思路: 不同于153,这个题目加了重复的数字,使用原来一样的code,example3过不了,nums[mid] == nums[r] 的情况,r -= 1,先前移动,退化为顺序查找。复杂度O(n).

    class Solution(object):
        def findMin(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            n = len(nums)
            l, r = 0, n-1
            while l < r:
                mid = int((l+r)/2)
                if nums[mid] < nums[r]:
                    r = mid
                elif nums[mid] == nums[r]:
                    r -= 1
                else:
                    l = mid+1       
            return nums[l]

    Reference: https://www.cnblogs.com/grandyang/p/4040438.html

    日期: 2021-04-11

  • 相关阅读:
    多国语言功能设计与实现
    锁标记
    Qt之生成Window资源文件(.rc 文件)
    如何获取本地html文件的标题
    Qt+gsoap调用WebService
    在Qt中使用ActiveX控件
    让notepad.exe的utf8不添加BOM
    Asp.Net生命周期系列四
    C#操作AD及Exchange Server总结
    C#彻底解决Web Browser 跨域读取Iframes内容
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14645478.html
Copyright © 2011-2022 走看看