665. Non-decreasing Array
2021/5/5 10:28:27
本文主要是介绍665. Non-decreasing Array,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Given an array nums
with n
integers, your task is to check if it could become non-decreasing by modifying at most one element.
We define an array is non-decreasing if nums[i] <= nums[i + 1]
holds for every i
(0-based) such that (0 <= i <= n - 2
).
Example 1:
Input: nums = [4,2,3] Output: true Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
Example 2:
Input: nums = [4,2,1] Output: false Explanation: You can't get a non-decreasing array by modify at most one element.
Constraints:
n == nums.length
1 <= n <= 104
-105 <= nums[i] <= 105
class Solution { public boolean checkPossibility(int[] nums) { // corner case if(nums == null || nums.length <= 1) return true; // the count of continuous non-decreasing sub-array int count = 1; int index = 0; int n = nums.length; for(int i = 1; i < n; i++){ if(nums[i] < nums[i - 1]){ index = i; count++; } } if(count == 1) return true; if(count == 2){ // if the discord happens at start or end position, we can modify // it to match the condition if(index == 1 || index == n - 1) return true; // if in the middle, we modify nums[index - 2] // index - 2, (index - 1, index) , index + 1 if(nums[index + 1] >= nums[index - 1] || nums[index] >= nums[index - 2]) { return true; } return false; } return false; } }
https://leetcode.com/problems/non-decreasing-array/discuss/106826/JavaC%2B%2B-Simple-greedy-like-solution-with-explanation
用count来表示non decreasing的subarray的数量,如果是1直接return true,如果大于2直接返回false。
如果是2,说明是两段。分两种情况,第一种要求转折点index有index + 1 >= index - 1, 或者index >= index - 2.
这篇关于665. Non-decreasing Array的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23增量更新怎么做?-icode9专业技术文章分享
- 2024-11-23压缩包加密方案有哪些?-icode9专业技术文章分享
- 2024-11-23用shell怎么写一个开机时自动同步远程仓库的代码?-icode9专业技术文章分享
- 2024-11-23webman可以同步自己的仓库吗?-icode9专业技术文章分享
- 2024-11-23在 Webman 中怎么判断是否有某命令进程正在运行?-icode9专业技术文章分享
- 2024-11-23如何重置new Swiper?-icode9专业技术文章分享
- 2024-11-23oss直传有什么好处?-icode9专业技术文章分享
- 2024-11-23如何将oss直传封装成一个组件在其他页面调用时都可以使用?-icode9专业技术文章分享
- 2024-11-23怎么使用laravel 11在代码里获取路由列表?-icode9专业技术文章分享
- 2024-11-22怎么实现ansible playbook 备份代码中命名包含时间戳功能?-icode9专业技术文章分享