leetcode——Find Peak Element
来源:互联网 发布:ubuntu16 安装软件 编辑:程序博客网 时间:2024/06/05 01:19
题目:
A peak element is an only 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.
思路:
题目中要找到比两边相邻的数字都大的数(峰值),而且在序列中有且仅有一个这样的数。
首先来建模,对于题目中的描述,不禁想到了y=-(x-a)^2+b的函数图像。
在题目中看来,不过是a有可能是所给数组的第一个或者最后一个值。
而对于仅仅有一个峰值的函数来说,峰值两边导数相反,而且峰值左边导数为正,右边为负。
因此为了达到logn的时间复杂度,可以进行二分法,即,分割之后若一边的导数为正,则峰值在另一边;反之亦然;知道刚好在分割的中点为峰值,则结束运算。
AC代码:
public int findPeakElement(int[] num) { if (num.length==1){ return 0; } if(num[0]>num[1]) return 0; if(num[num.length-1]>num[num.length-2]) return num.length-1; int left = 1,right = num.length-2; while(left<=right){ int mid = (left+right)>>1; if(num[mid]>num[mid-1] && num[mid]>num[mid+1]){ return mid; } else if(num[mid]>num[mid-1]){ left = mid+1; } else{ right = mid-1; } } return -1; }
0 0
- Find Peak Element—LeetCode
- leetcode——Find Peak Element
- leetcode 162 —— Find Peak Element
- Find Peak Element —— Leetcode
- leetcode——Find Peak Element
- [LeetCode] Find Peak Element
- Leetcode:Find Peak Element
- LeetCode Find Peak Element
- leetcode: Find Peak Element
- leetcode:Find Peak Element
- LeetCode Find Peak Element
- Find Peak Element --leetcode
- Leetcode Find Peak Element
- [LeetCode] Find Peak Element
- Leetcode Find Peak Element
- Leetcode: Find Peak Element
- 【leetcode】Find Peak Element
- leetcode:Find Peak Element
- C语言测试程序运行时间
- Android源码:(一) 安卓2.1到4.4操作系统通用的Actionbar实现的tab导航例子。
- 设计模式-代理模式
- ACM-Codeforces Round #280 (Div. 2)
- java_关键字
- leetcode——Find Peak Element
- Verdi/Ncverilog/VCS安装过程
- jspSmartUpload实现图片的批量上传
- 画板例子实现
- CSU 1503 点到圆弧的距离 (拉格朗日乘数法)
- 从NSM到Parquet:存储结构的衍化
- c++ 42面向对象表达式Scanner 实现
- Linux之Makefile(strip)
- Hardware Constraints