当前位置:网站首页>Non-decreasing Array
Non-decreasing Array
2022-08-09 08:04:00 【scwMason】
Given an array with n
integers, your task is to check if it could become non-deceasing by modifying at most1
element.
We define an array is non-deceasing if array[i] <= array[i + 1]
holds for every i
(1 <= i < n).
Example 1:
Input: [4,2,3]Output: TrueExplanation: You could modify the first4
to1
to get a non-deceasing array.
Example 2:
Input: [4,2,1]Output: FalseExplanation: You can't get a non-deceasing array by modify at most one element.
Note: The n
belongs to [1, 10,000].
The meaning of the title is to find a shortest non-descending subsequence. We can give a few examples to summarize:
Sequence: 1 4 2 3
In our thinking, there must be a process of comparing the magnitude of the two values before and after, which is correct, because if the sequence that begins to descend does not meet the requirements of the answer, just like when the loop reaches 2, we find that the4 is small, the sequence begins to decline, so we need to change the value here, which one to change, this is the point.Here we also need to give an example, you will see later
Sequence 3 4 2 5
We find that when we loop to 2, the previous 3 is greater than 2, while the first example is 1, which is smaller than 2.In sequence 1, because nums[i-2]<=nums[i], it means that only the first 4 does not satisfy the increment, so we need to change 4 to 2.In the second sequence, nums[i-2]>=nums[i], so it is necessary to turn 2 into 4 to satisfy.
So we can get ideas:
When nums[i-2]>=nums[i]: nums[i]=nums[i-1]
When nums[i-2]<=nums[i]: nums[i-1]=nums[i]
And when arr[i]
class Solution:def checkPossibility(self, nums: List[int]) -> bool:index=0#[3,4,2,3]for i in range(1,len(nums)):if nums[i]1):return Falseif i-2<0 or nums[i-2]<=nums[i]:nums[i-1]=nums[i]else:nums[i]=nums[i-1]return True
边栏推荐
猜你喜欢
随机推荐
ncnn 推理猫狗识别
OpenHarmony轻智能产品开发直播笔记
.net(三) 项目结构
Servlet的实现原理解析(serverapplet)(服务端程序)
BIM技术多牛逼?BIM技术在建筑工程行业的四大发展趋势
LeetCode·每日一题·761.特殊的二进制序列·分治
Operations in the database (syntax)
Talking about Flask_script
Unity 3D模型展示框架篇之资源打包、加载、热更(二)
The story of the disappearing WLAN of Windows 10 computers
Anaconda replaces the default virtual environment
.net(四) 数据层实现
图像处理(一)图像基础
HOOPS是什么?这4款3D软件开发工具包你还不知道?
RAID配置实战
mysql事务(详解)
C: print the diamond
scp上传文件到远程服务器
测试和开发之间的恩恩怨怨
我的创作纪念日