LeetCode(162):寻找峰值 Find Peak Element(Java)

234 篇文章 1 订阅
177 篇文章 0 订阅
这篇博客介绍了如何使用二分查找解决LeetCode上的寻找峰值问题,时间复杂度要求为O(logn)。博主分享了通过比较数组中值mid和mid+1来决定搜索范围的方法,并提供了问题的背景和解决方案。
摘要由CSDN通过智能技术生成

2019.8.20 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)

题目时间复杂度要求是o(lgn),因此需要考虑递归或者二分迭代来做。

如果将数组分为左右两部分,考察中值mid已经mid+1的大小。若mid更大则必有峰值出现在begin-mid之间,若mid较小则必有峰值出现在mid+1~end之间。由此可以进行二分迭代。


传送门:寻找峰值

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] = -∞.

峰值元素是指其值大于左右相邻值的元素。

给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。

数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。

你可以假设 nums[-1] = nums[n] = -∞。

示例 1:
输入: nums = [1,2,3,1]
输出: 2
解释: 3 是峰值元素,你的函数应该返回其索引 2。

示例 2:
输入: nums = [1,2,1,3,5,6,4]
输出: 1 或 5 
解释: 你的函数可以返回索引 1,其峰值元素为 2;
     或者返回索引 5, 其峰值元素为 6。
     
说明: 你的解法应该是 O(logN) 时间复杂度的。


/**
 *
 * 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] = -∞.
 * 峰值元素是指其值大于左右相邻值的元素。
 * 给定一个输入数组 nums,其中 nums[i] ≠ nums[i+1],找到峰值元素并返回其索引。
 * 数组可能包含多个峰值,在这种情况下,返回任何一个峰值所在位置即可。
 * 你可以假设 nums[-1] = nums[n] = -∞。
 *
 */

public class FindPeakElement {
    public int findPeakElement(int[] nums) {
        int begin = 0;
        int end = nums.length - 1;
        while(begin < end){
            int mid = (begin + end) >> 1;
            if(nums[mid] > nums[mid + 1]){
                end = mid;
            }else{
                begin = mid + 1;
            }
        }
        return end;
    }
}




#Coding一小时,Copying一秒钟。留个言点个赞呗,谢谢你#

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值