# 162 Find peak element
A peak element is an element that is strictly greater than its neighbors.
Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.
You may imagine that nums[-1] = nums[n] = -∞.
You must write an algorithm that runs in O(log n) time.
解题思路:
1.传统办法取中值后,比较中值左右邻值大小,中值都大过的话,return mid。
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
l, r = 0, len(nums)-1
while r > l:
mid = (r+l)//2
if nums[mid] > nums[mid+1]:
if nums[mid] > nums[mid-1]:
return mid
else:
r = mid
else:
l = mid + 1
return l
runtime:

36ms的solution是单边比较。

对三种Template的总结:
while循环之后,筛选剩下的元素个数。

如果是不用循环后的处理,也不用比较中值的左右邻大小,只是为了看符合要求的元素存不存在的话,用模板I。如果循环跑完也没有返回符合要求的元素值,说明不存在。

需要结合选定值和右邻值来判断,最后剩下一个值也要看符不符合条件。搜索space至少要有两个位。并且有筛选后的处理的话,用模板II。
要同时考虑选定值的左右邻值来判别来决定指针是左移还是右移。搜索空间至少要有三个位。最后会筛选剩下两个数。这种情况用模板III。
runtime都是O(logN), space complexity都是O(1)。

该博客讨论了如何使用二分查找算法在O(logN)的时间复杂度内找到整数数组中的峰值元素。峰值元素定义为大于其相邻元素的元素。文章提供了三种模板,分别对应不同的二分查找策略,并分析了它们的运行时间和空间复杂度。最终解决方案是通过比较中值与邻值来确定峰值元素的位置。
2668

被折叠的 条评论
为什么被折叠?



