665. Non-decreasing Array(python+cpp)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21275321/article/details/83864226

题目:

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

解释:
判断数组是否能在改变最多一个数字的情况下变成非递减序列。
当遇到nums[i]>nums[i+1]的情况,我们有两种选择使得数组非递减(局部):
1.把nums[i]降低为nums[i+1]
2.把nums[i+1]升高为nums[i]
如果可0.行的话,当然是选择优先把 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的情况,这里因为4比5之前的所有数字都大,所以可以把5降为4。
b. 1 4 5 3 6 7 --> 1 4 5 5 6 7
 当0.遇到5>3 的情况,这里3比5之前的4小,所以没有选择,只能把3 升为5。
需0.要第二次改动的时候,可以直接返回false,不需要把剩下的array走完。
0。
python代码:

class Solution(object):
    def checkPossibility(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        modified=False
        for i in range(len(nums)-1):
            if nums[i]>nums[i+1]:
                if modified:
                    return False
                if i<1 or nums[i+1]>nums[i-1]:
                    nums[i]=nums[i+1]
                else:
                    nums[i+1]=nums[i]
                modified=True
        return True

c++代码:

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

总结:

猜你喜欢

转载自blog.csdn.net/qq_21275321/article/details/83864226
今日推荐