博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
6. Find Peak Element
阅读量:5243 次
发布时间:2019-06-14

本文共 1149 字,大约阅读时间需要 3 分钟。

Find Peak Element

A peak element is an element that is greater than its neighbors.

Given an input array where num[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.

 

 

 

 

解法:

class Solution:

# @param num, a list of integer
# @return an integer
  def findPeakElement(self, num):
    if num is None:
      return None

    if not num:

      return None

    if len(num) == 1:

      return 0

    if len(num) == 2:

      if num[0] > num[1]:
        return 0
      else:
        return 1

    index = 0

    for i in range(1, len(num)-1):
      leftNum = num[i-1]
      currentNum = num[i]
      rightNum = num[i+1]
      if currentNum > leftNum and currentNum > rightNum:
        index = i
        break
    if index == 0:
      if num[0] > num[1]:
      index = 0
    if num[len(num)-2] < num[len(num)-1]:
      index = len(num) - 1

    return index

转载于:https://www.cnblogs.com/hechengzhu/p/4196383.html

你可能感兴趣的文章
MacOS copy图标shell脚本
查看>>
第八章 方法
查看>>
国外常见互联网盈利创新模式
查看>>
Oracle-05
查看>>
linux grep 搜索查找
查看>>
Not enough free disk space on disk '/boot'(转载)
查看>>
android 签名
查看>>
堆 栈
查看>>
Kth Smallest Element in Unsorted Array
查看>>
vue项目中使用百度统计
查看>>
android:scaleType属性
查看>>
SuperEPC
查看>>
RBAC用户角色权限设计方案
查看>>
thymeleaf
查看>>
CentOS7安装iptables防火墙
查看>>
mysql-5.7 innodb 的并行任务调度详解
查看>>
shell脚本
查看>>
Upload Image to .NET Core 2.1 API
查看>>
python针对excel的读写操作-----openpyxl
查看>>
最后几本书,不珍藏了。
查看>>