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. 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)),可以利用二分查找来做,只是这里更新搜索区间的时候不太一样:如果到mid的前一步是上坡而mid的下一步是下坡,那么mid即是山顶;如果mid的前一步和后一步都是上坡,那么山顶必然位于后半区间;如果mid的前一步和后一步都是下坡,那么山顶必然位于前半区间。除此之外,还需要处理边界问题。
我的C++代码实现如下:
int findPeakElement(const vector &num) {
int low = 0, high = num.size() - 1;
while (low <= high) {
int mid = (low + high) >> 1;
bool isUphillForward = (mid == 0 ? true : num[mid] > num[mid - 1]);
bool isUphillAfter = (mid == num.size() - 1 ? false : num[mid + 1] > num[mid]);
if (isUphillForward && !isUphillAfter) return mid;
else if (isUphillForward && isUphillAfter) low = mid + 1;
else high = mid - 1;
}
return low;
}
|