A peak element is an element that is greater than its neighbors.
Given an input array where <code>num[i] ≠ num[i+1]</code>, 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 <code>num[-1] = num[n] = -∞</code>.
For example, in array <code>[1, 2, 3, 1]</code>, 3 is a peak element and your function should return the index number 2.
<a href="https://oj.leetcode.com/problems/find-peak-element/">click to show spoilers.</a>
Credits:
这道题是求数组的一个峰值,这个峰值可以是局部的最大值,这里用遍历整个数组找最大值肯定会出现Time Limit Exceeded,我们要考虑使用类似于二分查找法来缩短时间,由于只是需要找到任意一个峰值,那么我们在确定二分查找折半后中间那个元素后,和紧跟的那个元素比较下大小,如果大于,则说明峰值在前面,如果小于则在后面。这样就可以找到一个峰值了,代码如下:
C++ 解法一:
Java 解法一:
下面这种解法就更加的巧妙了,由于题目中说明了局部峰值一定存在,那么实际上可以从第二个数字开始往后遍历,如果第二个数字比第一个数字小,说明此时第一个数字就是一个局部峰值;否则就往后继续遍历,现在是个递增趋势,如果此时某个数字小于前面那个数字,说明前面数字就是一个局部峰值,返回位置即可。如果循环结束了,说明原数组是个递增数组,返回最后一个位置即可,参见代码如下:
C++ 解法二:
Java 解法二: