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

posted @ 2021-04-11 20:56  summer_mimi  阅读(25)  评论(0编辑  收藏  举报