zoukankan      html  css  js  c++  java
  • 【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
    
    
  • 相关阅读:
    [USACO11JAN]Roads and Planes G【缩点+Dij+拓补排序】
    Cheatsheet: 2015 05.01 ~ 05.31
    Cheatsheet: 2015 04.01 ~ 04.30
    Cheatsheet: 2015 03.01 ~ 03.31
    Cheatsheet: 2015.02.01 ~ 02.28
    Cheatsheet: 2015 01.01~ 01.31
    Cheatsheet: 2014 12.01 ~ 12.31
    Cheatsheet: 2014 11.01 ~ 11.30
    Cheatsheet: 2014 10.01 ~ 10.30
    Cheatsheet: 2014 09.01 ~ 09.30
  • 原文地址:https://www.cnblogs.com/GoodRnne/p/10990917.html
Copyright © 2011-2022 走看看