边工作边刷题:70天一遍leetcode: day 6
Find Peak Element
要点:binary search的依据:三种情况之一:上坡,下坡和峰值点。边界条件和一般情况分开判断,这样branch不会很复杂。更简单的思路是只沿着上坡找。因为一定有peak存在所以最终的落点就是peak。
错误点:
- 因为invariant是low<high,所以mid+1不会越界
- 这题是类似binary search找上边界的算法。只有在循环最后更新mid,最终结果才在mid。如果先更新mid,结果是low(因为是上边界,low最后超过high)
class Solution(object):
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
low, high = 0, n-1
mid = low + (high-low)/2
while low<high:
if nums[mid]<nums[mid+1]:
low = mid+1
else:
high = mid
mid = low + (high-low)/2
return mid