根据题意峰值是相邻左侧和右侧数据均小于索引数据的值,则建立左右前缀数组,对左侧和右侧的值先行判断,最终左侧和右侧都符合的值即为峰值索引,代码如下
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param nums int整型一维数组
# @return int整型
#
class Solution:
def findPeakElement(self , nums: List[int]) -> int:
# write code here
l, r = [0] * len(nums), [0] * len(nums)
l[0] = r[-1] = 1
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
l[i] = 1
for i in range(len(nums) - 2, -1, -1):
if nums[i] > nums[i + 1]:
r[i] = 1
for i in range(len(nums)):
if l[i] == r[i] == 1:
return i
return -1