当前位置:网站首页>LeetCode:162. 寻找峰值
LeetCode:162. 寻找峰值
2022-07-06 08:44:00 【Bertil】
峰值元素是指其值严格大于左右相邻值的元素。
给你一个整数数组 nums,找到峰值元素并返回其索引。数组可能包含多个峰值,在这种情况下,返回 任何一个峰值 所在位置即可。
你可以假设 nums[-1] = nums[n] = -∞ 。
你必须实现时间复杂度为 O(log 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。
提示:
- 1 <= nums.length <= 1000
- -2^31 <= nums[i] <= 2^31 - 1
- 对于所有有效的 i 都有 nums[i] != nums[i + 1]
解题思路
1.首先找出最大的元素,然后返回其索引即可
2.解释:为什么最大值即答案?
- 因为题目中已经假设 nums[-1] = nums[n] = -∞,所以峰值不会在首尾元素出现
- 数组中的最大值左右相邻元素必定小于最大值
代码
/** * @param {number[]} nums * @return {number} */
var findPeakElement = function(nums) {
return nums.indexOf(Math.max(...nums))
};
边栏推荐
- Modify the video name from the name mapping relationship in the table
- How to conduct interface test? What are the precautions? Nanny level interpretation
- [brush questions] top101 must be brushed in the interview of niuke.com
- 电脑F1-F12用途
- 软件卸载时遇到trying to use is on a network resource that is unavailable
- JS native implementation shuttle box
- egg. JS getting started navigation: installation, use and learning
- pcd转ply后在meshlab无法打开,提示 Error details: Unespected eof
- Sublime text in CONDA environment plt Show cannot pop up the problem of displaying pictures
- Swagger setting field required is mandatory
猜你喜欢
TCP/IP协议
sublime text中conda环境中plt.show无法弹出显示图片的问题
ROS编译 调用第三方动态库(xxx.so)
Cisp-pte practice explanation
Tcp/ip protocol
Warning in install. packages : package ‘RGtk2’ is not available for this version of R
2022.02.13 - NC002. sort
Pointer advanced --- pointer array, array pointer
【ROS】usb_ Cam camera calibration
The harm of game unpacking and the importance of resource encryption
随机推荐
企微服务商平台收费接口对接教程
如何进行接口测试测?有哪些注意事项?保姆级解读
Revit 二次开发 HOF 方式调用transaction
Verrouillage [MySQL]
【MySQL】鎖
[cloud native topic -45]:kubesphere cloud Governance - Introduction and overall architecture of enterprise container platform based on kubernetes
Roguelike game into crack the hardest hit areas, how to break the bureau?
[MySQL] lock
vb.net 随窗口改变,缩放控件大小以及保持相对位置
2022.02.13 - NC004. Print number of loops
JVM performance tuning and practical basic theory - Part 1
The network model established by torch is displayed by torch viz
【MySQL】日志
Navicat premium create MySQL create stored procedure
堆排序详解
角色动画(Character Animation)的现状与趋势
marathon-envs项目环境配置(强化学习模仿参考动作)
egg. JS directory structure
Golang force buckle leetcode 1020 Number of enclaves
Unsupported operation exception