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 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; } };
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号:
![](https://images.cnblogs.com/cnblogs_com/pk28/1069498/o_qrcode_for_gh_db07a03aaa56_344.jpg)