Non-decreasing Array【非递减数列】

PROBLEM:

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

SOLVE:

/*
找到中心步骤为:用一个变量记录前一个值former(一开始不存在但需要比较,设为-1),比较当前值now和后一个值next大小。
如果递减{则判断去掉now是否可行,是则改变now和next的值;否则去掉next并直接改变next的值},
否则former=now;now=next;next=*(++iter)。只能去掉一次,用一个变量记录就行了。
*/
class Solution {
public:
    bool checkPossibility(vector<int>& nums) {
        bool tag=true;
        auto iter=nums.begin()+1;
        int former=-1,now=*(iter-1),next=*iter;    //数组中都为整数,否则former初始化为INT_MIN
        while(iter!=nums.end()){
            if(tag&&now>next){
                tag=false;
                if(former>next)
                    next=*(++iter);
                else{
                    now=next;
                    next=*(++iter);
                }
            }
            else if(now>next)
                return false;
            else{
                former=now;
                now=next;
                next=*(++iter);
            }
        }
        return true;
    }
};
用下标可能会使得程序更加简洁,但是速度没迭代器快,我使用迭代器进行求解
### 思路分析 “CF Edu Round 109 F Non - decreasing Array” 这道题通常是关于动态规划或者数据结构优化的问题。一般会给定一个数组,要求通过一些操作使得数组变成非递减数组,并且可能会有一些额外的限制条件,比如最小化操作的代价等。 ### 代码示例 以下是一个可能的 C++ 题解示例,由于没有具体题目描述,代码逻辑是一个通用的处理非递减数组的思路,假设需要通过修改数组元素使得数组非递减,并且要最小化修改的元素个数: ```cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; int minChangesToNonDecreasing(vector<int>& arr) { int n = arr.size(); vector<int> dp(n, 1); for (int i = 1; i < n; ++i) { for (int j = 0; j < i; ++j) { if (arr[j] <= arr[i]) { dp[i] = max(dp[i], dp[j] + 1); } } } int lisLength = *max_element(dp.begin(), dp.end()); return n - lisLength; } int main() { vector<int> arr = {3, 1, 2, 4, 5, 2, 6}; int result = minChangesToNonDecreasing(arr); cout << "Minimum changes to make the array non - decreasing: " << result << endl; return 0; } ``` ### 代码解释 1. **`minChangesToNonDecreasing` 函数**: - 首先初始化一个 `dp` 数组,`dp[i]` 表示以第 `i` 个元素结尾的最长非递减子序列的长度。 - 通过两层循环,外层循环遍历数组,内层循环遍历当前元素之前的所有元素。如果当前元素大于等于之前的元素,则更新 `dp[i]`。 - 最后找到 `dp` 数组中的最大值,即最长非递减子序列的长度。 - 用数组的长度减去最长非递减子序列的长度,得到需要修改的最少元素个数。 2. **`main` 函数**: - 定义一个测试数组 `arr`。 - 调用 `minChangesToNonDecreasing` 函数计算最少修改次数。 - 输出结果。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值