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.
s思路: 1. 這題看著沒難度啊。o(n)一遍,就出結果,出題肯定不是讓我給這個解答。也就意味著有o(lgn). 2. 確實可以用binary search。因為給的這個中間比兩邊大的要求,可以用來判斷binary search的走向。比如: 上圖,如果mid的位置是下坡,那么肯定有一個peak在mid的左側;如果mid的位置是上坡,那么肯定有一個peak在mid的右側。 3.這題給自己思維的啟發是:如果給的題目,看起來簡單,一下就有結果,通常就意味著出題的人需要更優化的結果,比如:簡單粗暴的做法有o(n^2),那么尋找看是否有o(nlgn)或o(n);簡單粗暴的做法有o(n),那么尋找看是否有o(lgn)!優化的關鍵,在我看來,不是炫技,而是打破潛意識的約束和限制,站在新的角度看問題而已,無所謂好壞!
新聞熱點
疑難解答