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.
Note:
Your solution should be in logarithmic complexity.
这道题要求给定一个相邻元素不相等的数据,找出局部最大值,并返回其对应下标。需要注意的是满足O(log N)的时间复杂度。
如果不考虑时间复杂度的限制,这道题相当简单了。从第一个元素开始,若其大于后续元素,则num[0]就是局部最大值之一,返回下标0即可;否则继续往后遍历,直到出现一个元素大于其相邻元素。
但是考虑到时间复杂度,很自然的想到二分查找,若中间元素大于相邻元素,则返回该中间元素的下标;否则,大于中间元素的那一侧必定存在局部最大元素。
二分查找的延续,但是我写的很啰嗦啊,后面也贴上较为简洁的写法。
int findPeakElement(const vector<int> &num) {
int len = num.size();
if (!len)
exit(1);
if (len == 1)
return 0;
if (len == 2){
if (num[0] > num[1])
return 0;
else
return 1;
}
int left = 0;
int right = len-1;
int mid = (left + right) / 2;
while (num[mid]<max(num[mid - 1], num[mid + 1])){
if (num[mid] < num[mid - 1]){
right = mid;
}
else{
left = mid ;
}
mid = (left + right) / 2;
if (mid == 0 || mid == len - 1)
return mid;
}
return mid;
}
//简洁版
int FindPeakElement(int num[],int len) {
int l = 0;
int r = len - 1;
int mid = (l + r) / 2;
while (l < r){
if (num[mid] < num[mid + 1]){
l = mid + 1;
}
else
r = mid;
mid = (l + r) / 2;
}
return l;
}
时间: 2024-10-31 12:42:44