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 解法二: