当前位置:网站首页>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))
};
边栏推荐
- Deep learning: derivation of shallow neural networks and deep neural networks
- Image, CV2 read the conversion and size resize change of numpy array of pictures
- logback1.3. X configuration details and Practice
- @JsonBackReference和@JsonManagedReference(解决对象中存在双向引用导致的无限递归)
- JVM quick start
- Synchronized solves problems caused by sharing
- 2022.02.13 - NC001. Reverse linked list
- 有效提高软件产品质量,就找第三方软件测评机构
- 个人电脑好用必备软件(使用过)
- Deep analysis of C language pointer
猜你喜欢
UnsupportedOperationException异常
Warning in install. packages : package ‘RGtk2’ is not available for this version of R
Using pkgbuild:: find in R language_ Rtools check whether rtools is available and use sys The which function checks whether make exists, installs it if not, and binds R and rtools with the writelines
Verrouillage [MySQL]
Crash problem of Chrome browser
可变长参数
visdom可视化实现与检查介绍
C语言双指针——经典题型
MySQL learning record 10getting started with JDBC
[MySQL] log
随机推荐
Swagger setting field required is mandatory
按位逻辑运算符
【嵌入式】Cortex M4F DSP库
2022.02.13 - NC001. Reverse linked list
sublime text没关闭其他运行就使用CTRL+b运行另外的程序问题
Computer cleaning, deleted system files
电脑清理,删除的系统文件
堆排序详解
Is it safe to open an account in Zheshang futures?
Trying to use is on a network resource that is unavailable
Research Report on Market Research and investment strategy of microcrystalline graphite materials in China (2022 Edition)
2022.02.13 - NC003. Design LRU cache structure
On the inverse order problem of 01 knapsack problem in one-dimensional state
2022.02.13 - NC004. Print number of loops
logback1.3. X configuration details and Practice
China's high purity aluminum target market status and investment forecast report (2022 Edition)
China vanadium battery Market Research and future prospects report (2022 Edition)
Sublime text using ctrl+b to run another program without closing other runs
电脑F1-F12用途
Analysis of the source code of cocos2d-x for mobile game security (mobile game reverse and protection)