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.

Note:

Your solution should be in logarithmic complexity.

因为按照题意,num[0]是大于左边的不存在的那个元素的,num[size-1]也是大于右边那个不存在的元素的,假如不存在,那么就会有num[0]<num[1],num[1]<num[2],就是增序,num[size-2]<num[size-1],这样num[size-1]就是peak elem了,所以一定存在。

于是就是这样的思路,num[NULL] < num[0],我们假设左边的元素小于右边的元素,那么第一个左边元素大于右边的那个一定是peak elem.如num[0].为什么第一个就是呢?因为前面的都是左<右,判断左>右为false。

注意:题目中说了,返回任意一个峰值都行,所以,能用二分搜索,如果要返回第一个峰值的话,二分搜索是不行的。

class Solution {
public:
int findPeakElement(vector<int>& nums) {
int left=,right=nums.size()-;
while(left<=right){
if(left==right)
return left;
int mid=(left+right)/;
if(nums[mid]<nums[mid+])
left=mid+;
else
right=mid;
} }
};

最新文章

  1. touchstart、touchmove、touchend 实现移动端上的触屏拖拽
  2. python opencv 实现Reinhard颜色迁移算法
  3. DIV+CSS 星号*
  4. 一加3,CM13蓝牙共享互联网 无效。
  5. 11g RAC R2 体系结构---进程,日志
  6. Matrix multiplication hdu4920
  7. [Leetcode] Container With Most Water ( C++)
  8. HTML系列(六):划分文档结构
  9. 查看Tomcat版本
  10. we7调用模板如何区分栏目页与详细页
  11. zookeeper源码分析-版本生成
  12. SP3精密星历简介
  13. 挖一挖不常用到而又很实用的重载-Split
  14. 用于水和水蒸汽物性计算的Python模块——iapws
  15. 最短寻道优先算法----SSTF算法
  16. 基于alpine制作php镜像
  17. iOS 开发 Tips
  18. NCBI通过氨基酸位置查看相邻SNP
  19. 【Django】Django-REST-Framework
  20. 动手动脑(Java)

热门文章

  1. webpack css压缩方案
  2. [zhuan]tomcat环境配置
  3. 复习java数据库操作的总结
  4. STL之二:vector容器用法详解
  5. select和epoll概念
  6. SpringMVC+MyBatis开发中指定callSettersOnNulls,可解决返回字段不全的问题
  7. Hadoop window win10 基础环境搭建(2.8.1)
  8. [POI2008]BLO-Blockade
  9. 项目记录 -- zfs get all [volume] python实现的数据构造
  10. Python模块学习 - Functools