• [LeetCode] 665. Non-decreasing Array


    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].


    Analyse

    给定一个大小为n的数组A,允许最多修改一个元素的值,判断能否变成一个非递减序列

    从左到右遍历数组,当遇到比前一个数A[i-1]小的数A[i]的时候,由于可以修改一个元素的值,可以将前一个数A[i-1]变小,A[i-1] = A[i-2]

    反映到代码里,直接判断当前数A[i]是否大于A[i-2]即可

    有一种不满足以上关系的情况(1-2<0)

    A[1] < A[0]

    比如{4, 2, 3},这种情况就直接忽略4,判断剩下的元素是否非递减的

    最终代码如下,这道题我提交了快10次,拿到了8个LeetCode的测试用例,最后看着Solution改自己的版本才AC了

    Think more, write less

    bool checkPossibility(vector<int>& nums)
    {
        int last = -100000;
        bool state = false;
        for (int i = 0; i < nums.size(); i++)
        {
            if (nums[i] >= last)
            {
                last = nums[i];
            }
            else
            {
                if (state) return false;
    
                if (i==1 || nums[i] >= nums[i-2])
                {
                    last = nums[i];
                }
    
                state = true;
            }
        }
    
        return true;
    }
    
  • 相关阅读:
    BZOJ BLO 1123 (割点)【双连通】
    P4291 [HAOI2008]排名系统
    P3165 [CQOI2014]排序机械臂
    P3224 [HNOI2012]永无乡
    P1169 [ZJOI2007]棋盘制作
    P2303 [SDOi2012]Longge的问题
    P2216 [HAOI2007]理想的正方形
    P2473 [SCOI2008]奖励关
    P2617 Dynamic Rankings
    P2518 [HAOI2010]计数
  • 原文地址:https://www.cnblogs.com/arcsinw/p/10661968.html
Copyright © 2020-2023  润新知