当前位置:网站首页>665.非递减数列
665.非递减数列
2022-07-30 05:38:00 【Linke66】
思路:
初始化一个bool类型的变量flag,true表示改动的次数未用,false表示改动的次数用掉了。
先看一下前两个元素是否满足非递减要求,不满足flag初始化为false。
从nums[1]开始,每次和后面一个元素比较,假如不满足非递减,就选择下面两种情况中的一个改变元素:
1 [3,5,4,6] 5>4且4>3,那么要把5变成4;即i=1,nums[i+1]>=nums[i-1]; nums[i]=nums[i+1];
2 [5,6,3,7] 6>3且3<5,那么要把3变成6;即i=1,nums[i+1]<nums[i-1]; nums[i+1]=nums[i];
class Solution {
public:
bool checkPossibility(vector<int>& nums) {
int n=nums.size();
if(n==1||n==2)return true;
bool flag=(nums[0]<=nums[1])?true:false;
for(int i=1;i<n-1;++i)
{
if(nums[i]>nums[i+1])
{
if(flag)
{
if(nums[i+1]>=nums[i-1])
{
nums[i]=nums[i+1];
}
else
{
nums[i+1]=nums[i];
}
flag=false;
}
else
{
return false;
}
}
}
return true;
}
};
边栏推荐
猜你喜欢
MySQL 用户授权
More fragrant open source projects than Ruoyi in 2022
使用DataEase开源工具制作一个高质量的数据大屏
406.根据身高重建队列
net start mysql MySQL 服务正在启动 . MySQL 服务无法启动。 服务没有报告任何错误。
[GO Language Basics] 1. Why do I want to learn Golang and the popularization of GO language entry
Programmers make money and practice, teach you how to do paid courses, self-media, paid articles and paid technical courses to make money
Frobenius norm(Frobenius 范数)
optimizer.zero_grad()
cmd (command line) to operate or connect to the mysql database, and to create databases and tables
随机推荐
【图像处理】基于中轴变换实现图像骨架提取附matlab代码
2022年比若依更香的开源项目
微积分 / 自动求导
腾讯面试居然跟我扯了半小时的CountDownLatch
[Mysql] CONVERT函数
CISP-PTE Zhenti Demonstration
Different lower_case_table_names settings for server (‘1‘) and data dictionary (‘0‘) 解决方案
配环境 / 初步测试
Ranking of grades (Huazhong University of Science and Technology postgraduate examination questions) (DAY 87)
PyCharm使用教程(较详细,图+文)
【图像检测】基于灰度图像的积累加权边缘检测方法研究附matlab代码
数据操作 / 数据预处理
[Koltin Flow (1)] Five ways to create flow
[GLib] What is GType
子查询作为检索表时的不同使用场景以及是否需要添加别名的问题
解决没有配置本地nacos但是一直发生localhost8848连接异常的问题
MySQL 数据库基础知识(系统化一篇入门)
Different lower_case_table_names settings for server ('1') and data dictionary ('0') solution
Thymeleaf简介
This dependency was not found: