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

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

Solution 1:

无逆序对必然true,只考虑存在逆序对情况:

条件1:逆序对最多为1, 逆序对数量1以上的必然不可能只修改一个数使全体有序( a b c ,其中a>b b>c,a>c,怎样修改b都只能将逆序对数量减少1)

条件2:逆序对数量为1,且该逆序对出现的位置为首部或者尾部都必然true(a b c ...,b以后均有序,只需修改a,令a<=b即可;... a b c,b之前均有序,只需修改c,令c>=b即可)

条件3:逆序对数量为1,且该逆序对出现位置在数列中部,即假设a[i-1]与a[i]为发现的不在首尾的唯一逆序对,                         考察a[i-2]  <= a[i-1] > a[i]  <= a[i+1] (= =先这么表示) 

情况1:a[i-2] > a[i],则即便修改a[i-1],使a[i-1]<=a[i], 但a[i-2]>a[i-1]依然存在逆序对  eg:3 4 2 4,修改a[i]

情况2:a[i-1]>a[i+1],则即便修改a[i],使a[i]>=a[i-1],但a[i]>a[i+1]依然存在逆序对 eg:3 7 5 6, 修改a[i-1]

情况1,2只出现其一,依然true,同时出现必为false

综上:在遍历的过程中,若逆序对数目超过1或者逆序对出现在中部且情况12同时出现,则false,否则true

Code:

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

猜你喜欢

转载自blog.csdn.net/lqy0927/article/details/81939693