Find Peak Elemen
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.
寻找峰值
你给出一个整数数组(size为n),其具有以下特点:
1. 相邻位置的数字是不同的
2. A[0] < A[1] 并且 A[n - 2] > A[n - 1]
3. 假定P是峰值的位置则满足A[P] > A[P-1]且A[P] > A[P+1],返回数组中任意一个峰值的位置下标。
注意事项
It’s guaranteed the array has at least one peak.
The array may contain multiple peeks, find any of them.
The array has at least 3 numbers in it.
样例
给出数组[1, 2, 1, 3, 4, 5, 7, 6]返回1, 即数值 2 所在位置, 或者6, 即数值 7 所在位置.
挑战
Time complexity O(logN)
标签
二分法 数组 谷歌
(1)C++
法①
#include
#include
#include
#include
using namespace std;
int LocalMaximum(const int* a, int size){
int left = 0, right = size - 1, mid;
while (left < right) {
mid = (left + right) / 2;
cout<< "mid: " << mid<if(a[mid]>a[mid+1]){
right = mid;
}else{
left = mid+1;//勿忘+1!!!
}
}
return left;
}
int main()
{
int a[] = {0,1,2,5,3,1};
int ret = LocalMaximum(a, sizeof(a)/sizeof(int));
cout<< "局部最大值下标:" << ret <return 0;
}
法②
#include
#include
#include
#include
using namespace std;
int LocalMaximum(const int* a, int size){
if(!a || size == 0) return -1;
int left = 0, right = size - 1, mid;
while (left + 1 < right) {
mid = (left + right) / 2;
cout<< "mid: " << mid<if(a[mid]>a[mid+1]){
right = mid;
}else{
left = mid;
}
}
return a[left] > a[right] ? left : right;
}
int main()
{
int a[] = {0,1,2,5,3,1};
int ret = LocalMaximum(a, sizeof(a)/sizeof(int));
cout<< "局部最大值下标:" << ret <return 0;
}
(2)Java
class Solution {
/**
* @param A: An integers array.
* @return: return any of peek positions.
*/
public int findPeak(int[] A) {
// write your code here
int start = 1, end = A.length-2; // 1.答案在之间,2.不会出界
while(start + 1 < end) {
int mid = (start + end) / 2;
if(A[mid] < A[mid - 1]) {
end = mid;
} else if(A[mid] < A[mid + 1]) {
start = mid;
} else {
end = mid;
}
}
if(A[start] < A[end]) {
return end;
} else {
return start;
}
}
}