【Leetcode】【Medium】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.

解题思路1:

直接想到的思路是,由于num[-1]是负无穷,因此num[0]对于它的previous neighbor是上升的,只需从num头开始遍历,找到第一个num[i] > num[i + 1]的数,那么i就是Peak Element;

算法虽然看上去已经很高效,但是,时间复杂度o(n);

代码:

 1 class Solution {
 2 public:
 3     int findPeakElement(const vector<int> &num) {
 4         int n = num.size();
 5         
 6         for (int i = 1; i < n; ++i) {
 7             if (num[i - 1] > num[i])
 8                 return i - 1;
 9         }
10         return n - 1;
11     }
12 };

解题思路2:

o(n)的时间复杂度还是可以继续优化的,o(n)继续优化,那就是思考有没有o(logn)的算法,比较常见出现logn的算法模式是:分治算法,二分搜索等,都是一个思路,一次考察数列的一半;

由于题目中说,对于多个peak element,我们只需找到一个就可以了;同时,由于num[-1] = num[n] = -∞,因此数组中至少有一个peak element;那么设置begin、mid、end三个index分别指向数组的起始,中间和结尾:

1、如果num[mid] > num[mid + 1],说明在begin和mid 之间,至少存在一个peak element,因此只考察数组前半段就可以了;

2、如果num[mid] < num[mid + 1], 说明在mid + 1和end之间,至少存在一个peak element,因此只考察数组后半段就可以了;

(原数组相邻元素都不相等,不用考察相等的情况)

另,为什么选择mid和mid+1比,而不是mid和mid-1比,因为begin始终小于end(循环条件),而mid取(begin + end) / 2,mid有可能等于begin,因此mid+1一定存在,而mid-1有可能越界;

因此,代码:

 1 class Solution {
 2 public:
 3     int findPeakElement(const vector<int> &num) {
 4         int begin = 0;
 5         int end = num.size() - 1;
 6         
 7         while (begin < end) {
 8             int mid = (begin + end) / 2;
 9             if (num[mid] > num[mid+1])
10                 end = mid;
11             else 
12                 begin = mid + 1;
13         }
14         
15         return begin;
16     }
17 };

但是实际运行中,思路2并不比思路1快多少,因为思路2在数据集中才能有效果,如果在小数据集,思路2的操作步骤比比思路1还要多,因此可能更慢;

原文地址:https://www.cnblogs.com/huxiao-tee/p/4285114.html