当前位置:网站首页>二分查找6 - 寻找峰值
二分查找6 - 寻找峰值
2022-08-03 05:25:00 【花开花落夏】
寻找峰值
一 题目
峰值元素是指其值严格大于左右相邻值的元素。
给你一个整数数组 nums,找到峰值元素并返回其索引。数组可能包含多个峰值,在这种情况下,返回 任何一个峰值 所在位置即可。
你可以假设 nums[-1] = nums[n] = -∞ 。
你必须实现时间复杂度为 O(log n) 的算法来解决此问题。
来源:力扣(LeetCode)

二 解题
注意看题目,所有有效的i,都有nums[i] != nums[i+1], 说明nums[]里的所有值都不相等。而nums[-1] = nums[n] = -∞,则表示只要沿着值大的方向走,总会存在峰值。使用二分法来实现这一过程。
当left=0,right=nums时,mid值偏向右,此时可以比较mid-1与mid;
当left=0,right=nums-1时,mid值偏向左,此时可以比较mid与mid+1.
class Solution {
public int findPeakElement(int[] nums) {
int left =0,right=nums.length-1,mid;
while(left<right){
mid = left + (right-left)/2;
if(nums[mid]>nums[mid+1]){
right = mid;
}else{
left = mid+1;
}
}
return left;
}
}
边栏推荐
- 常见的电子元器件分类介绍-唯样商城
- Automatic ticket issuance based on direct reduction of China Southern Airlines app
- MMU 介绍-[TBL/page table work]
- 自监督论文阅读笔记FIAD net: a Fast SAR ship detection network based on feature integration attention and self
- VS2022 encapsulation under Windows dynamic library and dynamic library calls
- PCB设计经验之模拟电路和数字电路区别为何那么大
- ZEMAX | 如何围绕空间中的任何点旋转任何元素
- ZEMAX | 探究 OpticStudio 偏振分析功能
- 电子元器件的分类有哪些?
- 卷积神经网络入门
猜你喜欢
随机推荐
opencv透视变化
NIO知识汇总 收藏这一篇就够了!!!
浮点型数据在内存中存储的表示
借助ginput函数在figure窗口实时读取、展示多条曲线的坐标值
自监督论文阅读笔记 Self-Supervised Deep Learning for Vehicle Detection in High-Resolution Satellite Imagery
自监督论文阅读笔记 Ship Detection in Sentinel 2 Multi-Spectral Images with Self-Supervised Learning
自监督论文阅读笔记Index Your Position: A Novel Self-Supervised Learning Method for Remote Sensing Images Sema
五、int和Integer有什么区别?
Convolutional Nerual Nertwork(CNN)
Windos 内网渗透之Token的使用
自监督论文阅读笔记 Multi-motion and Appearance Self-Supervised Moving Object Detection
全球一流医疗技术公司如何最大程度提高设计工作效率 | SOLIDWORKS 产品探索
增强光学系统设计 | Zemax 全新 22.2 版本产品现已发布!
pandoc -crossref插件实现markdwon文档转word后公式编号自定义
自监督论文阅读笔记 TASK-RELATED SELF-SUPERVISED LEARNING FOR REMOTE SENSING IMAGE CHANGE DETECTION
自监督论文阅读笔记 Self-supervised Label Augmentation via Input Transformations
微信小程序 自定义tabBar
MATLAB给多组条形图添加误差棒
【DC-5 Range Penetration】
ZEMAX | 如何创建复杂的非序列物体









