Given an array of integers. Find a peak element in it. An array element is peak if it is NOT smaller than its neighbors. For corner elements, we need to consider only one neighbor. For example, for input array {5, 10, 20, 15}, 20 is the only peak element. For input array {10, 20, 15, 2, 23, 90, 67}, there are two peak elements: 20 and 90. Note that we need to return any one peak element.
Following corner cases give better idea about the problem.
1) If input array is sorted in strictly increasing order, the last element is always a peak element. For example, 50 is peak element in {10, 20, 30, 40, 50}.
2) If input array is sorted in strictly decreasing order, the first element is always a peak element. 100 is the peak element in {100, 80, 60, 50, 20}.
3) If all elements of input array are same, every element is a peak element.
O(n)的方法就是线性扫描。用二分法,注意考虑corner elements。
int findPeak(int num[], int length) {
int start = 0;
int end = length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (num[mid] >= num[mid + 1] && num[mid] >= num[mid - 1]) {
return num[mid];
}
else if (num[mid] < num[mid - 1]) {
end = mid;
}
else {
start = mid;
}
}
if ((start == 0 || num[start] >= num[start - 1]) && num[start] >= num[start + 1]) {
return num[start];
}
else if ((end == length - 1 || num[end] >= num[end + 1]) && num[end] >= num[end - 1]) {
return num[end];
}
else {
return -1;
}
}
本文介绍了一种 O(n) 的方法来找到数组中一个或多个峰元素,即那些大于其相邻元素的元素。通过线性扫描和二分查找,文章详细解释了如何处理边界情况,如完全递增或递减序列,以及所有元素相同的情况。
198

被折叠的 条评论
为什么被折叠?



