Problem:
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.
Your solution should be in logarithmic complexity.
Summary:
找到数组中的局部最大数。
Solution:
1. 顺序查找:最直接的方法,复杂度为O(n)
class Solution {
public:
int findPeakElement(vector<int>& nums) {
int len = nums.size();
if (len == ) {
return ;
} for (int i = ; i < len; i++) {
if (!i && nums[i] > nums[i + ] ||
i == len - && nums[i] > nums[i - ] ||
nums[i] > nums[i - ] && nums[i] > nums[i + ]) {
return i;
}
} return -;
}
};
2. 二分查找:首先找到整体的中间值m,若m符合局部最大条件则返回m,否则若nums[m - 1] > nums[m]则在[0, m - 1]中查找。因为数组左边和右边为负无穷,所以在这种情况下[0, m - 1]中一定存在一个局部最大值。这种方法复杂度为O(logn)。
class Solution {
public:
int findPeakElement(vector<int>& nums) {
int len = nums.size();
if (len == ) {
return ;
} int l = , r = len - ;
while (l <= r) {
int m = (l + r) / ;
if ((!m || nums[m] >= nums[m - ]) &&
(m == len - || nums[m] >= nums[m + ])) {
return m;
}
if (m && nums[m] < nums[m - ]) {
r = m - ;
}
else {
l = m + ;
}
} return -;
}
};
二分查找的简略写法:
class Solution {
public:
int findPeakElement(vector<int>& nums) {
int len = nums.size();
if (len == ) {
return ;
} int l = , r = len - ;
while (l < r) {
int m = (l + r) / ;
if (nums[m] > nums[m + ]) {
r = m;
}
else {
l = m + ;
}
} return r;
}
};