当前位置:网站首页>力扣(LeetCode)162. 寻找峰值(2022.06.11)
力扣(LeetCode)162. 寻找峰值(2022.06.11)
2022-06-12 10:27:00 【ChaoYue_miku】
峰值元素是指其值严格大于左右相邻值的元素。
给你一个整数数组 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
-231 <= nums[i] <= 231 - 1
对于所有有效的 i 都有 nums[i] != nums[i + 1]
通过次数232,819提交次数470,577
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-peak-element
方法一:二分查找
C++提交内容:
class Solution {
public:
int findPeakElement(vector<int>& nums) {
int n = nums.size();
auto get = [=](int i) -> pair<int, int>{
if(i == -1 || i == n){
return {
0, 0};
}else{
return {
1, nums[i]};
}
};
int l = 0, r = n, index = 0;
while(l <= r){
int mid = (l + r) / 2;
if(get(mid - 1) < get(mid) && get(mid) > get(mid + 1)){
index = mid;
break;
}
if(get(mid) < get(mid + 1)){
l = mid + 1;
}else{
r = mid - 1;
}
}
return index;
}
};
边栏推荐
- [machine learning] practice of logistic regression classification based on Iris data set
- Malicious code analysis practice -- using apatedns and inetsim to simulate network environment
- How to refund the pre-sale deposit of JD 618 in 2022? Can JD 618 deposit be refunded?
- How the ArrayList collection implements ascending and descending order
- What can QA do in a "de QA" project?
- PHP uses RSA segment encryption and decryption method
- Leetcode 2169. Get operands of 0
- Set SVG color
- PHP curl function
- 学生管理系统
猜你喜欢

Class. Forname connection MySQL driver keeps throwing classnotfoundexception exception solution

Remote desktop cannot copy and paste solution

Bug easily ignored by recursion

Oculus quest generation opens Bluetooth connection

How the ArrayList collection implements ascending and descending order

On the improvement of 3dsc by harmonic shape context feature HSC

conda 安装tensorflow 测试tensorflow

Leetcode2154. 将找到的值乘以 2(二分查找)

Getting started with cloud API basics -- basic knowledge of picgo writing plug-ins

【机器学习】基于鸢尾花(iris)数据集的逻辑回归分类实践
随机推荐
ID obfuscation
On 3dsc theory and application of 3D shape context feature
Using the echart plug-in to dynamically refresh charts in uview/uni-app
基于QT的旅行查询与模拟系统
JS obtains the time period of this week and last week (one time period is from Monday to Sunday)
The name of a great man
[experiment] MySQL master-slave replication and read-write separation
One test for twoorthree years, recording some thoughts on test exchange experience
How to play the 2022 Taobao 618 Super Cat Games? Playing skills of 2022 Taobao 618 Cat Games
Win10 professional edition user name modification
VSCode代码调试技巧
93. 获得内网的所有IP地址
Chapter 3 search
Solution to the problem that the applet developer tool cannot input simplified Chinese
Set SVG color
Mobile terminal commissioning
JS string combination
4. creator mode
容器江湖的爱恨情仇
Leetcode2154. Multiply the found value by 2 (binary search)