[LeetCode] 153. Find Minimum in Rotated Sorted Array_Medium tag: Binary Search

Suppose an array sorted in ascending order 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.

You may assume no duplicate exists in the array.

Example 1:

Input: [3,4,5,1,2] 
Output: 1

Example 2:

Input: [4,5,6,7,0,1,2]
Output: 0

这个题目思路就是找到first number s.t <= nums[-1].利用Binary Search

T: O(lgn)

Code

class Solution:
    def minRotatedArray(self, nums):
        l, r, target = 0, len(nums) -1, nums[-1]
        if not nums: return -1
        while l + 1 < r:
            mid = l + (r - l)//2
            if nums[mid] <= target:
                r = mid
            else:
                l = mid
        return min(nums[l], nums[r])

猜你喜欢

转载自www.cnblogs.com/Johnsonxiong/p/9563702.html
今日推荐