# 162. Find Peak Element

A peak element is an element that is greater than its neighbors.

Given an input array `nums`, where `nums[i] ≠ nums[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 `nums[-1] = nums[n] = -∞`.

Example 1:

``````Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.
``````

Example 2:

``````Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5
Explanation: Your function can return either index number 1 where the peak element is 2,
or index number 5 where the peak element is 6.
``````

Note:

Your solution should be in logarithmic complexity.

C++ 解法一：

``````class Solution {
public:
int findPeakElement(vector<int>& nums) {
if (nums.size() == 1) return 0;
nums.insert(nums.begin(), INT_MIN);
nums.push_back(INT_MIN);
for (int i = 1; i < (int)nums.size() - 1; ++i) {
if (nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) return i - 1;
}
return -1;
}
};
``````

Java 解法一：

``````class Solution {
public int findPeakElement(int[] nums) {
if (nums.length == 1) return 0;
int[] newNums = new int[nums.length + 2];
System.arraycopy(nums, 0, newNums, 1, nums.length);
newNums[0] = Integer.MIN_VALUE;
newNums[newNums.length - 1] = Integer.MIN_VALUE;
for (int i = 1; i < newNums.length - 1; ++i) {
if (newNums[i] > newNums[i - 1] && newNums[i] > newNums[i + 1]) return i - 1;
}
return -1;
}
}
``````

C++ 解法二：

``````class Solution {
public:
int findPeakElement(vector<int>& nums) {
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] < nums[i - 1]) return i - 1;
}
return nums.size() - 1;
}
};
``````

Java 解法二：

``````public class Solution {
public int findPeakElement(int[] nums) {
for (int i = 1; i < nums.length; ++i) {
if (nums[i] < nums[i - 1]) return i - 1;
}
return nums.length - 1;
}
}
``````

C++ 解法三：

``````class Solution {
public:
int findPeakElement(vector<int>& nums) {
int left = 0, right = nums.size() - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] < nums[mid + 1]) left = mid + 1;
else right = mid;
}
return right;
}
};
``````

Java 解法三：

``````public class Solution {
public int findPeakElement(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] < nums[mid + 1]) left = mid + 1;
else right = mid;
}
return right;
}
}
``````

Peak Index in a Mountain Array

https://leetcode.com/problems/find-peak-element

https://leetcode.com/problems/find-peak-element/discuss/50232/find-the-maximum-by-binary-search-recursion-and-iteration

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation