LeetCode 665. 非遞減數列
阿新 • • 發佈:2021-02-09
技術標籤:刷題
難度:簡單。
雖然是簡單,但是這個題很容易錯啊,要想清楚各種情況。
錯誤結果的用例:
可參考題解 https://leetcode-cn.com/problems/non-decreasing-array/solution/3-zhang-dong-tu-bang-zhu-ni-li-jie-zhe-d-06gi/
正確解法:
class Solution {
public:
bool checkPossibility(vector<int>& nums) {
int n = nums.size();
int flag = 0;
for(int i = 1; i < n; i++){
if(flag > 1)return false;
if(nums[i] < nums[i - 1]){
if (i == 1 || nums[i] >= nums[i - 2]) {
nums[i - 1] = nums[i];
} else {
nums[i] = nums[i - 1];
}
flag++;
}
}
if(flag < 2)return true;
else return false;
}
};