LeetCode: 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.

click to show spoilers.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

SOLUTION 1:

线性查找,时间O(N):

 1 public int findPeakElement1(int[] num) {

 2         if (num == null) {

 3             return 0;

 4         }

 5         

 6         if (num.length == 1) {

 7             return 0;

 8         }

 9         

10         for (int i = 0; i < num.length; i++) {

11             if (i == 0) {

12                 if (num[i] > num[i + 1]) {

13                     return i;

14                 }

15                 continue;

16             }

17             

18             if (i == num.length - 1) {

19                 if (num[i] > num[i - 1]) {

20                     return i;

21                 }

22                 continue;

23             }

24             

25             if (num[i] > num[i + 1] && num[i] > num[i - 1]) {

26                 return i;

27             }

28         }

29         

30         return -1;

31     }
View Code

SOLUTION 2:

使用九章算法的二分法模板,可以达到O(logN)的时间复杂度。原理是:

当找到一个下坡,我们往左移动,当找到一个上坡,我们往右移动,这样我们就可以达到顶峰。

如果找到一个山谷,则向任意方向移动即可。

                      4

       3          3     5

    2    2    2

 1          1

如上图所示,3,4都是可能的解。

最后循环break时,把l,r的值找一个大的即可。

 1 public int findPeakElement(int[] num) {

 2         if (num == null) {

 3             return 0;

 4         }

 5         

 6         if (num.length == 1) {

 7             return 0;

 8         }

 9         

10         int l = 0;

11         int r = num.length - 1;

12         

13         while (l < r - 1) {

14             int mid = l + (r - l) / 2;

15             if (num[mid] > num[mid + 1] && num[mid] > num[mid - 1]) {

16                 return mid;

17             }

18             

19             if (num[mid] > num[mid - 1] && num[mid] < num[mid + 1]) {

20                 // rising area. move right;

21                 l = mid;

22             } else if (num[mid] < num[mid - 1] && num[mid] > num[mid + 1]) {

23                 r = mid;

24             } else {

25                 l = mid;                

26             }

27         }

28         

29         return num[l] > num[r] ? l: r;

30     }
View Code

 

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/binarySearch/FindPeakElement.java

你可能感兴趣的:(LeetCode)