首页 > 代码库 > LeetCode[Array]: Find Peak Element
LeetCode[Array]: Find Peak Element
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<int> &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; }
LeetCode[Array]: Find Peak Element
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。