题目
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
这段代码还是有其他改进的地方。
二分法
基础的代码在这儿,肯定不合适,需要对其进行修改。
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