zoukankan      html  css  js  c++  java
  • 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.

    题目大意, 判断原序列在至多修改一个位置后,能不能够成一个上升序列。

    我们只需要求原序列的最长上升序列的长度就可以了。如果n - 最长上升序列的长度 <= 1 那么就返回true。

    class Solution {
    public:
        bool checkPossibility(vector<int>& nums) {
            int n = nums.size();
            if (n == 1) return true;
            vector<int> d;
            d.emplace_back(nums[0]);
            for (int i = 1; i < nums.size(); ++i) {
                if (nums[i] >= d.back()) d.emplace_back(nums[i]);
                else {
                    int pos = lower_bound(d.begin(), d.end(), nums[i]) - d.begin();
                    if (pos >= d.size()) d.emplace_back(nums[i]);
                    else d[pos] = nums[i];
                }
            }
            //cout << d.size() << endl;
            if (n - d.size() <= 1) return true;
            return false;
        }
    };
  • 相关阅读:
    mysql 主从服务器配置
    Linux命令
    Kali
    Python进阶
    性能测试工具
    sphinx搜索
    页面静态化
    PHP API接口
    线程的生命周期
    多线程的创建
  • 原文地址:https://www.cnblogs.com/pk28/p/7445214.html
Copyright © 2011-2022 走看看