1. 程式人生 > >[LeetCode] Non-decreasing Array 非遞減數列

[LeetCode] Non-decreasing Array 非遞減數列

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

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

這道題給了我們一個數組,說我們最多有1次修改某個數字的機會,問能不能將陣列變為非遞減陣列。題目中給的例子太少,不能覆蓋所有情況,我們再來看下面三個例子:

4,2,3

-1,4,2,3

2,3,3,2

,4

我們通過分析上面三個例子可以發現,當我們發現後面的數字小於前面的數字產生衝突後,有時候需要修改前面較大的數字(比如前兩個例子需要修改4),有時候卻要修改後面較小的那個數字(比如前第三個例子需要修改2),那麼有什麼內在規律嗎?是有的,判斷修改那個數字其實跟再前面一個數的大小有關係,首先如果再前面的數不存在,比如例子1,4前面沒有數字了,我們直接修改前面的數字為當前的數字2即可。而當再前面的數字存在,並且小於當前數時,比如例子2,-1小於2,我們還是需要修改前面的數字4為當前數字2;如果再前面的數大於當前數,比如例子3,3大於2,我們需要修改當前數2為前面的數3。這是修改的情況,由於我們只有一次修改的機會,所以用一個變數cnt,初始化為1,修改數字後cnt自減1,當下次再需要修改時,如果cnt已經為0了,直接返回false。遍歷結束後返回true,參見程式碼如下:

class Solution {
public:
    bool checkPossibility(vector<int>& nums) {
        int cnt = 1, n = nums.size();
        for (int i = 1; i < n; ++i) {
            if (nums[i] < nums[i - 1]) {
                if (cnt == 0) return false;
                if (i == 1 || nums[i] >= nums[i - 2]) nums[i - 1] = nums[i];
                else nums[i] = nums[i - 1];
                --cnt;
            } 
        }
        return true;
    }
};

參考資料: