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;
        
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,769评论 0 33
  • 题目 给定一个整数数组,判定是否最多修改一个位置上的数字就可以让这个数组变成递增数组(包含等号)。 解析 基本思想...
    yxwithu阅读 317评论 0 0
  • 这题看似简单但是AC百分比很低,因为这题有两种情形:比如5,8,7,9和5,8,1,9都是i = 2的时候发现不满...
    DrunkPian0阅读 406评论 0 0
  • 前几日无事,就画了一幅好玩的禅绕画。今天整理好分享给大家。希望你们能喜欢~️ 1.工具 · 铅笔 · 针管笔 · ...
    xiyue手绘阅读 3,068评论 25 50
  • “ 酒入豪肠,七分酿成月光。剩下三分,啸成剑气,绣口一吐,就是半个盛唐。” 因上面这段话,“余光中”这个名字被我牢...
    喵喵僧阅读 880评论 0 9