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.
解题思路:
既然是rotated array, 原来的数组是依次增大的。在某个节点,比如从4开始到7被单独提出来rotated到了original list的前方。但7后面的数依然是依次增大的。所以以【0,1,2,4,5,6,7】来说,从2之后开始rotated,2是一个很重要的数字。在2之前一定有更小的数(ascending order),除非2就是最小的数。最基本的思路是,要在这个list里找到第一个比2小的数。
extremely condition:
no sort list [1,2,3,4,5,6], find first number smaller than 6.
Generally, find:
first number<=last number in the list, 找到第一个比list中最后一个数小的数。在这里就是0
以下是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]
两种方法性能差不多