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 }