代码改变世界

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

2018-08-31 06:53  Johnson_强生仔仔  阅读(258)  评论(0编辑  收藏  举报

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])