mycode 54.81%
class Solution(object): def findPeakElement(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return None if len(nums) == 1 or nums[0]>nums[1] : return 0 if nums[-1] > nums[-2]: return len(nums)-1 for i in range(1,len(nums)-1): if nums[i] > nums[i-1] and nums[i] > nums[i+1]: return i
参考:
思路:题目中左右为负无穷这个条件可以用起来,把原列表扩增以下就可以把两端的情况合并在一个for循环讨论啦
import math class Solution(object): def findPeakElement(self, nums): """ :type nums: List[int] :rtype: int """ nums = [-float('inf')] + nums + [-float('inf')] for i in range(1, len(nums)-1): if nums[i-1] < nums[i] > nums[i+1]: return i-1