Python解法
首先得了解面试官的意图,这题用顺序搜索肯定不行,因此应该用二分。关于二分边界定义,这里有一篇好文,复习一下。
Note:1.考虑已经排好序的情况,初始化mid为0。
二分有一种特例,就是left=mid=right,此时无法判断前后,需采用顺序查找。
#《剑指Offer》思路
# -*- coding:utf-8 -*-
class Solution:
def minNumberInRotateArray(self, rotateArray):
def helper(r, left, right):
res = r[left]
for i in range(left, right+1):
if r[i] < res:
res = r[i]
return res
if not rotateArray:return 0
r = rotateArray
left, right, mid = 0, len(rotateArray)-1, 0#考虑已经排好序的情况
while r[left] >= r[right]:
if right - left == 1:
mid = right
break
mid = left + (right-left)/2
if r[left] == r[right] and r[mid] == r[left]:
return helper(r, left, right)
if r[mid] >= r[left]:
left = mid
elif r[mid] <= r[right]:
right = mid
return r[mid]
#另类解法
class Solution:
def minNumberInRotateArray(self, rotateArray):
# write code here
if not rotateArray:return 0
r = rotateArray
left, right = 0, len(rotateArray)-1
while left < right:
mid = left + (right-left)/2
if r[mid-1]>r[mid]:#前面应该小
return r[mid]
if r[mid]>r[mid+1]:#后面应该大
return r[mid+1]
if r[mid]>r[left] and r[mid]>r[right]:
left = mid
if r[mid]<r[right] and r[mid]<r[left]:
right = mid
考点
附录:(二分模板)
#可以在非递减序列中,查找某元素第一次出现的位置。
left, right = -1, n
while left+1 != right:
mid = (left + right) / 2
if array[mid] >= v:
right = mid
else:
left = mid
if right == n || array[right] != v:
return -1
return right