LeetCode-Non-decreasing Array

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/82831167

Description:
Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.

We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n).

Example 1:

Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.

Example 2:

Input: [4,2,1]
Output: False
Explanation: You can't get a non-decreasing array by modify at most one element.

Note:

  • The n belongs to [1, 10,000].

题意:给定一个一维数组array,判断是否最多进行一次修改可以让整个数组为非递减排序,即对于任何的i(0<=i<n),满足array[i] <= array[i + 1];

解法:如果可以修改成功,那么最终整个数组满足array[i] <= array[i + 1],因此,我们遍历数组,对于array[i] > array[i + 1]的情况我们可以修改的是array[i]或者是array[i + 1]使其满足非递减的排序;有下面两种情况;

  • 对于array[i + 1] < array[i - 1],如果我们修改了array[i],还是不满足整个数组非递减,只能修改array[i + 1]
  • 对于array[i + 1] >= array[i - 1],如果修改了array[i + 1],可能对后面的结果元素产生影响,只能修改array[i]
Java
class Solution {
    public boolean checkPossibility(int[] nums) {
        int cnt = 0;
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] > nums[i + 1]) {
                cnt++;
                if (i > 0 && nums[i + 1] < nums[i - 1]) {
                    nums[i + 1] = nums[i];
                }
            }
            if (cnt > 1) {
                return false;
            }
        }
        return true;
    }
}

所有代码都托管在GitHub;

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/82831167