665. Non-decreasing Array

題目描述:

給定一個有n個整數的數組,檢查它是否可以通過修改最多一個元素使它變得非遞減數組

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

這道題看着很簡單,但是AC率很低,那是因爲沒有想到全面的情形,比如我自己舉了一個例子

5 8 7 9
5 8 1 9

這兩個都是到8的時候不滿足升序了,但是前者是改變8,後者是改變1。

所以這道題難在當遇到nums[i] > nums[i+1]的時候,是把nums[i]降爲nums[i+1] 還是將nums[i+1]升爲nums[i].

如果可行的話,當然是選擇優先把 nums[i]降爲nums[i+1],這樣可以減少 nums[i+1] > nums[i+2] 的風險。

  來看一下兩種情況:

 a. 1 3 5 4 6 7  -->  1 3 4 4 6 7

    當遇到5 > 4 的情況,這裏因爲45 之前的所有數字都大,所以可以把5 降爲4。

 b. 1 4 5 3 6 7  -->  1 4 5 5 6 7

    當遇到5 > 3 的情況,這裏35之前的4小,所以沒有選擇,只能把3 升爲5

代碼:

package array;


/*


                                665. 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).

 */

public class NondecreasingArray {
    public boolean checkPossibility(int[] nums) {

        int count = 0;
        for (int i = 0; i < nums.length-1; i++) {
            if (nums[i] > nums[i+1]){
                count++;
                if (i > 0 && nums[i + 1] < nums[i - 1]) nums[i + 1] = nums[i];
                else nums[i] = nums[i + 1];
            }
        }

        return count <= 1;
    }

    public static void main(String[] args) {

        int[] nums = {3,4,2,3};
        System.out.println(new NondecreasingArray().checkPossibility(nums));

    }

}
發佈了95 篇原創文章 · 獲贊 141 · 訪問量 41萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章