《中英双解》leetCode Find Peak Element(寻找峰值的元素)

162. Find Peak Element

难度中等662收藏分享切换为中文接收动态反馈

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

Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.

You may imagine that nums[-1] = nums[n] = -∞.

You must write an algorithm that runs in O(log n) time.

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: 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.

Constraints:

  • 1 <= nums.length <= 1000
  • -231 <= nums[i] <= 231 - 1
  • nums[i] != nums[i + 1] for all valid i.

通过次数174,411提交次数351,484

这题的思路是用二分法,可能大家接触的二分法都是有序的元素,这一题其实就是求区域峰值问题,简单点说,跟我们高中学弟单调性有点像,所有每个最大值都代表了一个峰值,我们只要找到那个中间位置的元素,就意味着可以一直使用二分法进行求解

class Solution {
    public int findPeakElement(int[] nums) {
        
        int low = 0;
        int high = nums.length - 1;
        return Helper(nums,low,high);
    }

    public int Helper(int[] num,int low,int high){
    //真正的输出   
    if(low == high)
        return low;
    else {
        //中间元素
        int mid1 = (low+high)/2;
        //中间元素的后一个元素
        int mid2 = mid1+1;
        if(num[mid1] > num[mid2])
            return Helper(num, low, mid1);
        else
            return Helper(num, mid2, high);
       }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值