class Solution {
public:
bool checkPossibility(vector<int>& nums) {
int n = nums.size();
for(int i=0;i<n-1;i++){
int x = nums[i],y = nums[i+1];
if(x>y){
//后面向前面看齐
nums[i]=y;
if(is_sorted(nums.begin(),nums.end())){
return true;
}
//前面向后面看齐
nums[i] = x;
nums[i+1]=x;
return is_sorted(nums.begin(),nums.end());
}
}
return true;
}
};
简化版
class Solution {
public:
bool checkPossibility(vector<int>& nums) {
int n = nums.size();
int cnt = 0;
for (int i = 0; i < n - 1; i++) {
int x = nums[i], y = nums[i + 1];
if (x > y) {
cnt++;
if (cnt > 1) return false;
//如果下面成立那么就应该y看向
if (i > 0 && nums[i - 1] > y) {
nums[i + 1] = x;
}
}
}
return true;
}
};
标签:cnt,return,数列,nums,int,665,true,LeetCode
From: https://www.cnblogs.com/poteitoutou/p/16885165.html