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;
        }
    };
  • 相关阅读:
    002使用代码和未经编译的XMAL文件创建WPF程序
    001使用代码创建WPF应用程序
    制作地图PPT
    数据库基本知识学习(sql server)
    虚拟现实技术对人类是福还是祸?
    计算机中的数学
    软件架构
    extracts
    bootstrap
    omron欧姆龙自动化应用
  • 原文地址:https://www.cnblogs.com/pk28/p/7445214.html
Copyright © 2011-2022 走看看