Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.python
(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.spa
解题思路:code
既然是rotated array, 原来的数组是依次增大的。在某个节点,好比从4开始到7被单独提出来rotated到了original list的前方。但7后面的数依然是依次增大的。因此以【0,1,2,4,5,6,7】来讲,从2以后开始rotated,2是一个很重要的数字。在2以前必定有更小的数(ascending order),除非2就是最小的数。最基本的思路是,要在这个list里找到第一个比2小的数。element
extremely condition:rem
no sort list [1,2,3,4,5,6], find first number smaller than 6. it
Generally, find:io
first number<=last number in the list, 找到第一个比list中最后一个数小的数。在这里就是0ast
如下是python代码实现:
class Solution(object): def findMin(self, nums): """ :type nums: List[int] :rtype: int """ first,end=0,len(nums)-1 while (first<end): mid=first+(end-first)/2 if nums[mid]<=nums[end]: end=mid else: first=mid+1 return nums[first]
# 还有另外一种方法,是找到第一个比nums[0]小的数。
def findMin(self, nums): # write your code here if len(nums)==0: return -1 if nums[0]<nums[-1]: return nums[0] start = 0 end = len(nums) - 1 while start+1<end: mid = (start+end)//2 if nums[mid]>nums[0]: start = mid if nums[mid]<=nums[0]: end = mid if nums[start]>nums[end]: return nums[end] else: return nums[start]
两种方法性能差很少