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:

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

Example 2:

  1. Input: nums = [1,2,1,3,5,6,4]
  2. Output: 1 or 5
  3. Explanation: Your function can return either index number 1 where the peak element is 2,
  4.   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++ 解法一:

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

Java 解法一:

  1. class Solution {
  2. public int findPeakElement(int[] nums) {
  3. if (nums.length == 1) return 0;
  4. int[] newNums = new int[nums.length + 2];
  5. System.arraycopy(nums, 0, newNums, 1, nums.length);
  6. newNums[0] = Integer.MIN_VALUE;
  7. newNums[newNums.length - 1] = Integer.MIN_VALUE;
  8. for (int i = 1; i < newNums.length - 1; ++i) {
  9. if (newNums[i] > newNums[i - 1] && newNums[i] > newNums[i + 1]) return i - 1;
  10. }
  11. return -1;
  12. }
  13. }

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

C++ 解法二:

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

Java 解法二:

  1. public class Solution {
  2. public int findPeakElement(int[] nums) {
  3. for (int i = 1; i < nums.length; ++i) {
  4. if (nums[i] < nums[i - 1]) return i - 1;
  5. }
  6. return nums.length - 1;
  7. }
  8. }

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

C++ 解法三:

  1. class Solution {
  2. public:
  3. int findPeakElement(vector<int>& nums) {
  4. int left = , right = nums.size() - ;
  5. while (left < right) {
  6. int mid = left + (right - left) / ;
  7. if (nums[mid] < nums[mid + ]) left = mid + ;
  8. else right = mid;
  9. }
  10. return right;
  11. }
  12. };

Java 解法三:

  1. public class Solution {
  2. public int findPeakElement(int[] nums) {
  3. int left = , right = nums.length - ;
  4. while (left < right) {
  5. int mid = left + (right - left) / ;
  6. if (nums[mid] < nums[mid + ]) left = mid + ;
  7. else right = mid;
  8. }
  9. return right;
  10. }
  11. }

类似题目:

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. iOS UIGestureRecognizer与UIMenuController(内容根据iOS编程)

    UIGestureRecognizer 对象会截取本应由视图处理的触摸事件.当某个UIGestureRecognizer对象识别出特定的手势后,就会向指定的对象发送指定的消息.iOS SDK默认提供若 ...

  2. LINQ to SQL语句(17)之对象加载

    对象加载 延迟加载 在查询某对象时,实际上你只查询该对象.不会同时自动获取这个对象.这就是延迟加载. 例如,您可能需要查看客户数据和订单数据.你最初不一定需要检索与每个客户有关的所有订单数据.其优点是 ...

  3. .NET缓存框架CacheManager在混合式开发框架中的应用(1)-CacheManager的介绍和使用

    在我们开发的很多分布式项目里面(如基于WCF服务.Web API服务方式),由于数据提供涉及到数据库的相关操作,如果客户端的并发数量超过一定的数量,那么数据库的请求处理则以爆发式增长,如果数据库服务器 ...

  4. Redis命令拾遗五(有序集合)

    本文版权归博客园和作者吴双本人共同所有,博客园蜗牛NoSql系列分享 http://www.cnblogs.com/tdws/tag/NoSql/ Sorted Set 有序集合—Sorted Set ...

  5. Debian8安装Vim8

    1 安装vim需要的库 apt-get build-dep vim-gtk apt-get install libncurses5-dev mercurial   2 下载Vim8 apt-get i ...

  6. 【转】将grub2安装到u盘的方法

    将grub2安装到u盘的方法 时间:2015-03-21来源:linux网站 作者:linux人 grub2在各大linux发行版中广泛采用,它非常强大,基本上大多数操作系统都是通过它引导起来的,它的 ...

  7. python学习笔记(基础三:if else流程判断、while循环、for循环)

    if else流程判断 getpass在pycharm中无法使用,在命令行窗口中进入python环境可以使用. import getpassusername = input("usernam ...

  8. DbMigration使用方法

    1.Enable-Migrations -ContextTypeNameLITCS.Data.gmisContext Enable-Migrations  命令创建了一个新的Migrations文件夹 ...

  9. swift 如何在IOS应用图标上添加消息数

    在应用图标右上角添加消息数提醒,可以很方便的告知用户该应用中有无新消息需要处理.下面用xcode 7.3.1来简要说明一下如何用swift语言进行此功能的实现. 1.修改 AppDelegate.sw ...

  10. 如果把带有html的标记的字符串从服务端传到页面上,需要对其进行编码。Ajax.JavaScriptStringEncode()

    controller: StringBuilder s = new StringBuilder(); string a = "<script>alert('我StringBuil ...