当前位置:网站首页>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))
};
边栏推荐
- 2022.02.13 - 238. Maximum number of "balloons"
- visdom可视化实现与检查介绍
- logback1.3. X configuration details and Practice
- Research Report on supply and demand and development prospects of China's high purity aluminum market (2022 Edition)
- marathon-envs项目环境配置(强化学习模仿参考动作)
- Process of obtaining the electronic version of academic qualifications of xuexin.com
- swagger设置字段required必填
- Leetcode question brushing (5.31) string
- Purpose of computer F1-F12
- Precise query of tree tree
猜你喜欢

Cisp-pte practice explanation
![[embedded] cortex m4f DSP Library](/img/83/ab421d5cc18e907056ec2bdaeb7d5c.png)
[embedded] cortex m4f DSP Library

Generator parameters incoming parameters

Image, CV2 read the conversion and size resize change of numpy array of pictures

visdom可视化实现与检查介绍

JS inheritance method

MySQL learning records 12jdbc operation transactions
![[MySQL] log](/img/e9/1617122888c096cf6aba2bdb88f0ef.png)
[MySQL] log

Chrome浏览器的crash问题

可变长参数
随机推荐
查看局域网中电脑设备
egg. JS getting started navigation: installation, use and learning
JVM 快速入门
Sublime text using ctrl+b to run another program without closing other runs
企微服务商平台收费接口对接教程
Revit 二次开发 HOF 方式调用transaction
目标检测——Pytorch 利用mobilenet系列(v1,v2,v3)搭建yolov4目标检测平台
MySQL learning record 07 index (simple understanding)
Research Report on Market Research and investment strategy of microcrystalline graphite materials in China (2022 Edition)
Deep analysis of C language pointer
Deep analysis of C language data storage in memory
View computer devices in LAN
Sort according to a number in a string in a column of CSV file
【MySQL】锁
堆排序详解
After PCD is converted to ply, it cannot be opened in meshlab, prompting error details: ignored EOF
Roguelike游戏成破解重灾区,如何破局?
Unified ordering background interface product description Chinese garbled
China vanadium battery Market Research and future prospects report (2022 Edition)
PLT in Matplotlib tight_ layout()