p162

LeetCode p162 Find Peak Element 题解

1.题目:

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.

题意:

给你一个数组,找出那个比它左右两个相邻的数都大的数的下标。

2.解题思路:

见代码,遍历一次。

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 
public class Solution {
public int findPeakElement(int[] nums) {
int n = nums.length;
if (n < 2)
return 0;
if (nums[0] > nums[1])
return 0;
if (nums[n - 1] > nums[n - 2])
return n - 1;
for (int i = 1; i < n - 1; i++) {
if (nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) {
return i;
}
}
return 0;
}
}

4.一些总结: