Leetcode 665. 非递减数列

原题链接:Leetcode 665. Non-decreasing Array

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

We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).

Example 1:

Input: nums = [4,2,3]
Output: true

Explanation: You could modify the first 4 to 1 to get a non-decreasing array.

Example 2:

Input: nums = [4,2,1]
Output: false

Explanation: You cannot get a non-decreasing array by modifying at most one element.

Constraints:

  • n == nums.length
  • 1 <= n <= 104
  • -105 <= nums[i] <= 105

题目大意:

给了一个有n个元素的数组nums,问能否仅改变一个元素一次,使得序列变成非递减序列

方法一:遍历

思路:

原先我认为只要判断比前一个元素小的元素个数即可,也过了样例,但还是错了。像[3, 4, 2, 3] 就满足只有一个元素比前一个元素小,无法通过一次调整变为非递减序列。

nums[i] < nums[i - 1]时,主要可以分为三种情况:

  1. 例如[4, 2, 5] , 此时i = 1, 可以将4 调小,也可以将 2调到4或者5
  2. 例如1, 4, 2, 5,此时i > 1,可以将4调小,也可以将2调大
  3. 例如3, 4, 2, 5,此时nums[i] >= nums[i - 2],只能将2调大

C++ 代码:

class Solution {
public:
    bool checkPossibility(vector<int>& nums) {
        int count = 0;  // 调整次数
        for(int i = 1; i < nums.size(); i++ ){
            if(nums[i] < nums[i - 1]){  // 出现了破坏非递减的元素
                if(i == 1 || nums[i] >= nums[i - 2]){ 
                    nums[i - 1] = nums[i];
                }
                else{
                    nums[i] = nums[i - 1];
                }
                count++;
            }
        }

        return count <= 1;  // 判断调整次数是否超过1次
    }
};

复杂度分析:

  • 时间复杂度:O(n),遍历一遍数组
  • 空间复杂度:O(1)
  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值