题目
A peak element is an element that is greater than its neighbors.
Given an input array wherenum[i] ≠ num[i+1]
, find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that num[-1] = num[n] = -∞
.
For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
这个题目需要说明的是,该数组里的值,有3种情况:
- 单增
- 单减
- 先增,后减
扫描数组
如果nums[i]>nums[i-1] and nums[i] > nums[max]
, 则 max = i
class Solution(object):
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max = 0
for i in range(1, len(nums)):
if nums[i] > nums[i - 1] and nums[i] > nums[max]:
max = i
return max
这段代码还是有其他改进的地方。
二分法
基础的代码在这儿,肯定不合适,需要对其进行修改。二分法的思路是,不断的将搜索的范围缩小,所以端点如何移动是至关重要的。
- 如果nums[mid] > nums[mid] + 1,则[left,mid]是下一个需要寻找的数组范围。不管数组是不是单调的,最大值均在此范围内。
- 同理,如果nums[mid] < nums[mid] + 1, 则[mid, right]是下一个需要寻找的数组范围。
- 哪什么时候取
left <= right
还是left < right
,这个需要根据具体的问题进行调整,最简单的方法是,给个数组,依据上面的规则,运算一遍。
class Solution(object):
def findPeakElement2(self, nums):
l, r = 0, len(nums) - 1
while l < r:
mid = l + (r - l) // 2
if nums[mid] > nums[mid + 1]:
r = mid
else:
l = mid + 1
return l