Non-decreasing Array

昨天第一次参加LeetCode Weekly Contest, 一道题没有做出来。所有时间都花在第一道题上了,被虐得很惨。 看了一下别人的参考代码,理解之后发现真的很简单。

  1. Non-decreasing Array

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 to1 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里面找到逆序的元素,也就是nums[i] > nums[i + 1], 用reversOrder来记录逆序的个数。如果个数超过1,则不可能通过改一个元素就变成正序,所以返回false; 如果目前是第一个逆序,则讨论两种情况:

  • nums[i – 1] <= nums[i + 1],比如[1,6,2,3,4]里6 > 2 并且5 > 2这种情况,要改正的话将6改成1或者2能满足题意;但如果写6改成2就可以同时包括i == 0的情况;
  • nums[i – 1] > nums[i + 1], 比如[5,6,2,3,4]里6 > 2并且 5 > 2这种情况,肯定是改2为6才能将此处的逆序改为正序。但这个例子的情况是改为[5,6,6,3,4]之后仍然有逆序,下次循环reverseOrder != 0也会返回false.
class Solution {
    public boolean checkPossibility(int[] nums) {
        int n = nums.length;
        if (n <= 2){
            return true;
        }
        int reverseOrder = 0;
        for (int i = 0; i < n - 1; i++){
            if (nums[i] > nums[i + 1]){
                if (reverseOrder != 0){
                    return false;
                } else {
                    if (i == 0 || nums[i - 1] <= nums[i + 1]){
                        nums[i] = nums[i + 1];
                    } else {
                        nums[i + 1] = nums[i];
                    }
                    reverseOrder++;
                }
            } 
        }
        return true;
        
    }
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/c101c46e68dc
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞