【LeetCode每天一题】Find Peak Element(找到峰值元素)
A peak element is an element that is greater than its neighbors.Given an input array nums
, where nums[i] ≠ nums[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 nums[-1]= nums[n] =-∞
.
Example 1:
Input: nums =[1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.
Example 2:
Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5
Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
思路
这道题让我们求所谓的峰值,就是左边和右边的元素都小于中间的值,列表中可能存在多个这种值。这道题最简单的办法就是从头到尾遍历查找,如果 当前元素大于左右的元素直接返回,一直遍历。另外因为第一个元素左边和最后一个元素的右边都是假定无穷小,因此也要加上该情况的判断。时间复杂度为O(n), 空间复杂度为O(1)。
解决代码
1 class Solution(object):
2 def findPeakElement(self, nums):
3 """
4 :type nums: List[int]
5 :rtype: int
6 """
7 if not nums or len(nums) == 1:
8 return 0
9 for i in range(len(nums)):
10 if (i == 0 and nums[i] >nums[i+1]) or (i == len(nums)-1 and nums[i] > nums[i-1]):
11 return i
12 if nums[i] > nums[i-1] and nums[i] > nums[i+1]:
13 return i