1. 程式人生 > >LeetCode-Non-decreasing Array

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

題意:給定一個一維陣列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;