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.spa
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.code
You may imagine that num[-1] = num[n] = -∞
.blog
For example, in array [1, 2, 3, 1]
, 3 is a peak element and your function should return the index number 2.ip
O(n) 很好作:element
1 public class Solution { 2 public int findPeakElement(int[] num) { 3 if(num == null || num.length == 0) return -1; 4 if(num.length == 1) return 0; 5 for(int i = 0; i < num.length; i ++){ 6 if(i == 0 && num[0] > num[1]) return 0; 7 else if(i == num.length - 1 && num[i] > num[i - 1]) return i; 8 else if(i > 0 && i < num.length -1 && num[i - 1] < num[i] && num[i] > num[i + 1]) return i; 9 } 10 return -1; 11 } 12 }
這題要求咱們在一個無序的數組裏面找到一個peak元素,所謂peak,就是值比兩邊鄰居大就好了。input
對於這題,最簡單地解法就是遍歷數組,只要找到第一個元素,大於兩邊就能夠了,複雜度爲O(N)。但這題還能夠經過二分來作。it
首先咱們找到中間節點mid,若是大於兩邊返回當前index就能夠了,若是左邊的節點比mid大,那麼咱們能夠繼續在左半區間查找,這裏面必定存在一個peak,爲何這麼說呢?假設此時的區間範圍爲[0, mid - 1], 由於num[mid - 1]必定大於num[mid]了,若是num[mid - 2] <= num[mid - 1],那麼num[mid - 1]就是一個peak。若是num[mid - 2] > num[mid - 1],那麼咱們就繼續在[0, mid - 2]區間查找,由於num[-1]爲負無窮,因此最終咱們絕對能在左半區間找到一個peak。同理右半區間同樣。io
O(nlogn):function
1 public class Solution { 2 public int findPeakElement(int[] num) { 3 if (num == null || num.length == 0){ 4 return 0; 5 } 6 if (num.length == 1){ 7 return 0; 8 } 9 int srt = 0; 10 int end = num.length - 1; 11 while (srt <= end){ 12 int mid = srt + (end - srt) / 2; 13 if (mid - 1 > -1 && num[mid] < num[mid - 1]){ 14 end = mid - 1; 15 } else if (mid + 1 < num.length && num[mid] < num[mid + 1]){ 16 srt = mid + 1; 17 } else { 18 return mid; 19 } 20 } 21 return 0; 22 } 23 }