# [LeetCode] 162. Find Peak Element 求数组的局部峰值

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

Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.

You may imagine that nums[-1] = nums[n] = -∞.

You must write an algorithm that runs in O(log n) time.

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

Constraints:

• 1 <= nums.length <= 1000
• -2^31 <= nums[i] <= 2^31 - 1
• nums[i] != nums[i + 1] for all valid i.

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;
}
}

Github 同步地址：

https://github.com/grandyang/leetcode/issues/162

Peak Index in a Mountain Array

Find a Peak Element II

Pour Water Between Buckets to Make Water Levels Equal

Count Hills and Valleys in an 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 题目讲解汇总(持续更新中...)

posted @ 2015-01-11 21:53  Grandyang  阅读(24530)  评论(14编辑  收藏  举报