A peak element is an element that is greater than its neighbors.

Given an input array nums, where nums[i] ≠ nums[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 nums[-1] = nums[n] = -∞.

Example 1:

Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.

Example 2:

Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5
Explanation: Your function can return either index number 1 where the peak element is 2,
  or index number 5 where the peak element is 6.

Note:

Your solution should be in logarithmic complexity.

这道题是求数组的一个峰值,如果这里用遍历整个数组找最大值肯定会出现Time Limit Exceeded,但题目中说了这个峰值可以是局部的最大值,所以我们只需要找到第一个局部峰值就可以了。所谓峰值就是比周围两个数字都大的数字,那么只需要跟周围两个数字比较就可以了。既然要跟左右的数字比较,就得考虑越界的问题,题目中给了nums[-1] = nums[n] = -∞,那么我们其实可以把这两个整型最小值直接加入到数组中,然后从第二个数字遍历到倒数第二个数字,这样就不会存在越界的可能了。由于题目中说了峰值一定存在,那么有一个很重要的corner case我们要注意,就是当原数组中只有一个数字,且是整型最小值的时候,我们如果还要首尾垫数字,就会形成一条水平线,从而没有峰值了,所以我们对于数组中只有一个数字的情况在开头直接判断一下即可,参见代码如下:

C++ 解法一:

class Solution {
public:
int findPeakElement(vector<int>& nums) {
if (nums.size() == ) return ;
nums.insert(nums.begin(), INT_MIN);
nums.push_back(INT_MIN);
for (int i = ; i < (int)nums.size() - ; ++i) {
if (nums[i] > nums[i - ] && nums[i] > nums[i + ]) return i - ;
}
return -;
}
};

Java 解法一:

class Solution {
public int findPeakElement(int[] nums) {
if (nums.length == 1) return 0;
int[] newNums = new int[nums.length + 2];
System.arraycopy(nums, 0, newNums, 1, nums.length);
newNums[0] = Integer.MIN_VALUE;
newNums[newNums.length - 1] = Integer.MIN_VALUE;
for (int i = 1; i < newNums.length - 1; ++i) {
if (newNums[i] > newNums[i - 1] && newNums[i] > newNums[i + 1]) return i - 1;
}
return -1;
}
}

我们可以对上面的线性扫描的方法进行一些优化,可以省去首尾垫值的步骤。由于题目中说明了局部峰值一定存在,那么实际上可以从第二个数字开始往后遍历,如果第二个数字比第一个数字小,说明此时第一个数字就是一个局部峰值;否则就往后继续遍历,现在是个递增趋势,如果此时某个数字小于前面那个数字,说明前面数字就是一个局部峰值,返回位置即可。如果循环结束了,说明原数组是个递增数组,返回最后一个位置即可,参见代码如下:

C++ 解法二:

class Solution {
public:
int findPeakElement(vector<int>& nums) {
for (int i = ; i < nums.size(); ++i) {
if (nums[i] < nums[i - ]) return i - ;
}
return nums.size() - ;
}
};

Java 解法二:

public class Solution {
public int findPeakElement(int[] nums) {
for (int i = 1; i < nums.length; ++i) {
if (nums[i] < nums[i - 1]) return i - 1;
}
return nums.length - 1;
}
}

由于题目中提示了要用对数级的时间复杂度,那么我们就要考虑使用类似于二分查找法来缩短时间,由于只是需要找到任意一个峰值,那么我们在确定二分查找折半后中间那个元素后,和紧跟的那个元素比较下大小,如果大于,则说明峰值在前面,如果小于则在后面。这样就可以找到一个峰值了,代码如下:

C++ 解法三:

class Solution {
public:
int findPeakElement(vector<int>& nums) {
int left = , right = nums.size() - ;
while (left < right) {
int mid = left + (right - left) / ;
if (nums[mid] < nums[mid + ]) left = mid + ;
else right = mid;
}
return right;
}
};

Java 解法三:

public class Solution {
public int findPeakElement(int[] nums) {
int left = , right = nums.length - ;
while (left < right) {
int mid = left + (right - left) / ;
if (nums[mid] < nums[mid + ]) left = mid + ;
else right = mid;
}
return right;
}
}

类似题目:

Peak Index in a Mountain Array

参考资料:

https://leetcode.com/problems/find-peak-element

https://leetcode.com/problems/find-peak-element/discuss/50232/find-the-maximum-by-binary-search-recursion-and-iteration

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Find Peak Element 求数组的局部峰值的更多相关文章

  1. [LintCode] Find Peak Element 求数组的峰值

    There is an integer array which has the following features: The numbers in adjacent positions are di ...

  2. LeetCode Find Peak Element 找临时最大值

    Status: AcceptedRuntime: 9 ms 题意:给一个数组,用Vector容器装的,要求找到一个临时最高点,可以假设有num[-1]和num[n]两个元素,都是无穷小,那么当只有一个 ...

  3. LeetCode Find Peak Element

    原题链接在这里:https://leetcode.com/problems/find-peak-element/ 题目: A peak element is an element that is gr ...

  4. LeetCode Find Peak Element [TBD]

    说要写成对数时间复杂度,算了想不出来,写个O(n)的水了 class Solution { public: int findPeakElement(const vector<int> &a ...

  5. LeetCode: Find Peak Element 解题报告

    Find Peak Element A peak element is an element that is greater than its neighbors. Given an input ar ...

  6. [LeetCode] Find Peak Element 二分搜索

    A peak element is an element that is greater than its neighbors. Given an input array where num[i] ≠ ...

  7. ✡ leetcode 169. Majority Element 求出现次数最多的数 --------- java

    Given an array of size n, find the majority element. The majority element is the element that appear ...

  8. leetcode——169 Majority Element(数组中出现次数过半的元素)

    Given an array of size n, find the majority element. The majority element is the element that appear ...

  9. Lintcode: Find Peak Element

    There is an integer array which has the following features: * The numbers in adjacent positions are ...

随机推荐

  1. ASP.NET Core 中文文档 第三章 原理(12)托管

    原文:Hosting 作者:Steve Smith 翻译:娄宇(Lyrics) 校对:何镇汐.许登洋(Seay) 为了运行 ASP.NET Core 应用程序,你需要使用 WebHostBuilder ...

  2. 调用webservice进行身份验证

    因为同事说在调用webservice的时候会弹出身份验证的窗口,直接调用会返回401,原因是站点部署的时候设置了身份验证(账号名称自己配置).因而在调用的时候需要加入身份验证的凭证. 至于如何获取身份 ...

  3. img标签使用绝对路径无法显示图片

    说明:  图片的磁盘路径斜杠使用:右斜杠"\",而图片的网络路径使用左斜杠"/",注意加以区分. 如果这张图片属于服务器图片或者网络图片,我们必须在Img标签里 ...

  4. C# - 多线程 之 Process与Thread与ThreadPool

    Process 进程类, // 提供对本地和远程进程的访问,启动/停止本地系统进程 public class Process : Component { public int Id { get; } ...

  5. [Android]Dagger2Metrics - 测量DI图表初始化的性能(翻译)

    以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/5098943.html Dagger2Metrics - 测量D ...

  6. [转]HttpModule的认识

    HttpModule是向实现类提供模块初始化和处置事件.当一个HTTP请求到达HttpModule时,整个ASP.NET Framework系统还并没有对这个HTTP请求做任何处理,也就是说此时对于H ...

  7. BigCouch资料整理

    BigCouch架构 CHTTPD 封装了FABIC接口,CouchDB在HTTP层的集群操作 FABRIC  CouchDB集群的操作代理. 主要用于控制CouchDB集群,Erlang层面的操作 ...

  8. Myeclipse开发环境下文件中出现的提示错误与解决方法:The import javax.servlet cannot be resolved?

    1.开发工具:MyEclipse 2.右击项目  >>  Build Path  >>  Add External Archives (Tomcat  >>  li ...

  9. ORA-00600 3020 ORA-10567案例

    PlateSpin克隆复制出的Oracle数据库服务器,往往启动数据库实例都会遇到一些杂七杂八的问题.今天测试DR环境时又遇到了一个特殊场景,在此之前,我已经遇到了下面两起案例: ORA-00600: ...

  10. cstore_fdw的安装使用以及源码分析

    一.cstore_fdw的简介 https://github.com/citusdata/cstore_fdw,此外部表扩展是由citusdata公司开发,使用RC_file格式对数据进行列式存储. ...