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 first4
to1
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; } };