前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 162. Find Peak Element

LeetCode 162. Find Peak Element

原创
作者头像
大学里的混子
修改2018-10-29 17:04:20
6700
修改2018-10-29 17:04:20
举报
文章被收录于专栏:LeetCodeLeetCode

162.Find Peak Element

代码语言:javascript
复制

    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.

题目大意:在一个数组中寻找一个峰值,题目的最后一句话是一个关键,如果没有这句话,我想大多数首先想到的就是一个一个的判断,这样的话算法复杂度是O(n),实际上本题目只要求找到一个符合要求的就可以,题目中也明确的要求对数的算法复杂度,所以可以考虑利用二分查找法。

代码语言:javascript
复制
This problem is similar to Local Minimum. And according to the given condition, 
num[i] != num[i+1], there must exist a O(logN) solution. So we use binary search for this problem.
If num[i-1] < num[i] > num[i+1], then num[i] is peak
If num[i-1] < num[i] < num[i+1], then num[i+1...n-1] must contains a peak
If num[i-1] > num[i] > num[i+1], then num[0...i-1] must contains a peak
If num[i-1] > num[i] < num[i+1], then both sides have peak
(n is num.length)

首先对断点值进行判断,如果符合题意直接返回即可。不难写出基于循环的二分搜索。

代码语言:javascript
复制
   public int findPeakElement(int[] nums) {
        int left = 1,right = nums.length-2;
        int mid = 0;
        if (nums.length==1|| nums[1]< nums[0]) return 0;
        if (nums[nums.length-2]<nums[nums.length-1]) return nums.length-1;
        while (left <= right){
            mid = left+(right -left)/2;
            if (nums[mid]>nums[mid+1]&& nums[mid]>nums[mid-1]) return mid;
            else if (nums[mid]>nums[mid+1]&& nums[mid]<nums[mid-1]) right = mid-1;
            else if (nums[mid]<nums[mid+1]&& nums[mid]>nums[mid-1]) left = mid+1;
            else right = mid-1;
        }
        return -1;
    }

总结:针对与以后做这种寻找满足条件的某个数的题目,都可以考虑用二分法降低时间复杂度。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 162.Find Peak Element
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档