其他分享
首页 > 其他分享> > 0665. Non-decreasing Array (M)

0665. Non-decreasing Array (M)

作者:互联网

Non-decreasing Array (M)

题目

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:


题意

给定一个数组,判断能否通过改变其中一个或零个数,使整个数组构成非递减序列。

思路

遍历数组,找到第一个i,使得 nums[i] > nums[i+1],这时我们尝试进行修复,有两种情况,要么改变nums[i],要么改变nums[i+1]:(1) i - 1 >= 0 且 nums[i-1] > nums[i+1],这时为了保证非递减,必须使 nums[i+1] = nums[i]; (2) i == 0 或者 nums[i-1] <= nums[i+1] 时,为了在之后的遍历中尽可能保证非递减,nums[i+1]必须尽可能的小,所以使 nums[i] = nums[i+1]。完成修复后,我们已经保证了子数组 [0 ~ i+1] 是一个非递减序列,且已经动用了唯一的修改机会,只要继续向后遍历判断是否仍存在 nums[j] > nums[j+1] 的情况即可。


代码实现

Java

class Solution {
    public boolean checkPossibility(int[] nums) {
        boolean found = false;
        for (int i = 0; i + 1 < nums.length; i++) {
            if (nums[i] > nums[i + 1]) {
                if (found) return false;
                found = true;
              	// 因为只有改变nums[i+1]才会影响之后的遍历,可以省略改变nums[i]的情况
                if (i > 0 && nums[i - 1] > nums[i + 1]) nums[i + 1] = nums[i];
            }
        }
        return true;
    }
}

标签:non,nums,array,Non,decreasing,found,Array,true,0665
来源: https://www.cnblogs.com/mapoos/p/14729677.html