classSolution:deffindPeakElement(self,nums: List[int]) ->int:iflen(nums)==1:return0 l =0 r =len(nums)-1while l < r: mid = l + (r - l) //2if nums[mid]< nums[mid +1]: l = mid +1else: r = mid # 大于等于证明前面有peakreturn l # 注意是l
一次遍历
deffindPeak(arr) : n =len(arr)# first or last element is peak elementif (n ==1) :return0if (arr[0]>= arr[1]) :return0if (arr[n -1]>= arr[n -2]) :return n -1# check for every other elementfor i inrange(1, n -1):# check if the neighbors are smallerif (arr[i]>= arr[i -1]and arr[i]>= arr[i +1]) :return i
classSolution(object):deffindPeakElement(self,nums): for i inrange(1, len(nums)):if nums[i -1]> nums[i]:return i -1returnlen(nums)-1
二分搜索
找到中间mid元素后,和后面的元素比较大小,如果大于,则说明峰值在前面,如果小于则在后面
classSolution:deffindPeakElement(self,nums: List[int]) ->int: l =0 r =len(nums)-1while l < r -1: mid = (l + r) //2if nums[mid]> nums[mid+1]and nums[mid]> nums[mid-1]:return mid if nums[mid]< nums[mid+1]: l = mid +1else: r = mid -1return l if nums[l]>= nums[r]else r