Find Peak Element

Find Peak Element

 

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.

我自己写的就比较挫一点了,这道题要用二分查找来实现。但我一直没有明白为什么可以用二分查找实现

 1 public class Solution {
 2     public int findPeakElement(int[] num) {
 3         if(num.length == 0 || num.length == 1)
 4             return 0;
 5         boolean isIncr = false;                    //是否为升序
 6         int index = -1;                            //peak索引值
 7         int numArray[] = new int[num.length + 2];
 8         for(int i = 0; i < num.length;i++){
 9             numArray[i + 1] = num[i];
10         }
11         numArray[0] = Integer.MIN_VALUE;
12         numArray[numArray.length - 1] = Integer.MIN_VALUE;
13         
14         for(int i = 1; i < numArray.length;i++){
15             if(numArray[i] > numArray[i - 1])
16                 isIncr = true;
17             if(isIncr && numArray[i]  < numArray[i - 1]){
18                 index = i - 2;
19                 break;
20             }
21         }
22         
23         return index;
24     }
25 }

下面这个是百度到的,好像是CSDN还是哪儿的,我就懒得去找源出处了。这个时间复杂度是O(N)

1 public class Solution {
2     public int findPeakElement(int[] num) {
3         for(int i = 1; i < num.length; i++){
4             if(num[i] < num[i - 1])
5                 return i - 1;
6         }
7         return num.length - 1;
8     }
9 }

下面这个是讨论区用二分查找实现的

 1 public class Solution {
 2     public int findPeakElement(int[] num) {
 3         int low = 0;
 4         int high = num.length - 1;
 5         while (low < high) {
 6             int mid = (low + high + 1)/2;
 7             if (mid == 0 || num[mid] > num[mid-1]) {
 8                 low = mid;
 9             } else {
10                 high = mid-1;
11             }
12         }
13         return low;
14     }
15 }

 

posted on 2014-12-18 19:46  luckygxf  阅读(163)  评论(0编辑  收藏  举报

导航