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

相关文章:

  • 2021-09-08
  • 2022-01-18
  • 2021-06-24
  • 2021-11-22
  • 2021-10-11
  • 2022-01-02
  • 2021-12-06
  • 2021-12-20
猜你喜欢
  • 2022-03-04
  • 2021-09-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案