[LeetCode162]Find Peak Element

来源:互联网 发布:圆弧倒角和刀具的算法 编辑:程序博客网 时间:2024/05/16 01:29

题目来源:https://leetcode.com/problems/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.

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.

click to show spoilers.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

最容易想到的方法就是自左至右遍历数组,如果某元素比他左右元素都大,则返回该顶点。

class Solution162{public:int findPeakElement(vector<int>& nums){//顺序查找int n = nums.size();if (n == 1)return 0;else if (nums[0] > nums[1])return 0;else if (nums[n - 1] > nums[n - 2])return n - 1;for (int i = 1; i < n - 1; ++i){if (nums[i - 1] <= nums[i] && nums[i + 1] <= nums[i])return i;}return -1;}};

另一种方法是使用二分查找法解决问题。这个方法利用了题目中的如下性质:

1)最左边的元素,它“更左边”的元素比它小(负无穷),我们认为它是一个增长的方向

2)最右边的元素,它“更右边”的元素比它小(也是负无穷),我们认为它是一个下降的方向

根据这两点我们可以判断:最左边和最右边的元素围成的区域内,必有至少一个顶点

现在我们找到中点 nums[mid],将它与 nums[mid + 1] 作比较,如果前者较小,则方向是增长,与最左边的元素是一致的,就把左边界挪到mid+1的位置;

否则与最右边的元素一致,将右边界挪到mid的位置。

这个方法的原理就是当左边界方向为“增长”,右边界方向为“下降”时,二者围出的区域必有一个顶点。


class Solution162{public:int findPeakElement(vector<int>& nums){//二分查找int n = nums.size();if (n == 1)return 0;int left = 0;int right = n - 1;int mid = 0;while (left < right){//注意该处是<mid = (left + right) / 2;if (nums[mid] <= nums[mid + 1])left = mid + 1;else{right = mid;}}return left;}};int main(){Solution164 soulution;vector<int> v = { 1, 2, 3, 1 };cout << soulution.findPeakElement(v);system("pause");return 0;}













0 0
原创粉丝点击