题目:
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.
思路:
刚开始自己用的是线性扫描的方法,结果发现O(n)的时间复杂度不符合题目要求。二分查找是一个更好的算法:对于中位数,如果nums[mid] > nums[mid + 1],那么可以推断出在[left, mid]区间内必然存在至少一个peak,因为最左边的数值被当作了负无穷大;而如果nums[mid] < nums[mid + 1],那么同理可以推断出在[mid + 1, right]区间内必然存在至少一个peak,因为最右边的数值被当作了负无穷大。我们可以不断以二分的手段缩小区间,直到达到平凡情况。算法的时间复杂度是O(logn)。
代码:
class Solution {
public:
int findPeakElement(vector<int>& nums) {
if (nums.size() == 0) {
return -1;
}
int left = 0, right = nums.size() - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] > nums[mid + 1]) {
right = mid;
}
else {
left = mid + 1;
}
}
return left;
}
};