首页 > 代码库 > leetcode 【 Find Minimum in Rotated Sorted Array 】python 实现

leetcode 【 Find Minimum in Rotated Sorted Array 】python 实现

题目

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.

You may assume no duplicate exists in the array.

 

代码:oj测试通过 Runtime: 52 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         # short lenght case 9         if len(num)==1 :10             return num[0]11         # binary search12         start = 013         end = len(num)-114         while start<=end :15             if start==end :16                 return num[start]17             if start+1==end :18                 return min(num[start],num[end])19             mid = (start+end)/220             if num[mid]>num[start] :21                 if num[mid]>num[end] :22                     start = mid23                 else:24                     return num[start]25             else:26                 if num[mid]>num[end] :27                     return num[end]28                 else:29                     end = mid

 

思路

基本思路还是binary search。

注意修改start或end时的条件:因为mid也有可能是最小值,所以start=mid end=mid,这个跟传统二分查找时start=mid+1以及end=mid-1有所不同。

想明白这些后,代码一次AC。

leetcode 【 Find Minimum in Rotated Sorted Array 】python 实现