Special thanks to @ts for adding this problem and creating all test cases.
这题是MIT open course ware的第一节课上讲的例题,解法有很多,最好的是二分法查询。
要考虑的边界条件有
1. 只有一个element的情况
2. 整个序列只有Increasing 和decreasing的情况
代码如下:
class Solution: # @param num, a list of integer # @return an integer def findPeakElement(self, num): low=0 high=len(num)-1 if high==low: return 0 while low<high: mid=low+(high-low)/2 if num[mid]>num[mid+1] and num[mid]>num[mid-1]: return mid if num[mid]>num[mid+1]: high=mid-1 elif num[mid]<=num[mid+1]: low=mid+1 return low