
class Solution
{
public:
bool checkPossibility(vector<int> &nums)
{
int n = nums.size(), 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;
}
if (i > 0 && y < nums[i - 1])
{
nums[i + 1] = x;
}
}
}
return true;
}
};
该博客探讨了一段C++代码,用于检查给定数组中元素的顺序是否可以通过至多一次交换变得非递减。函数通过遍历数组并计数逆序对来实现,若逆序对超过一次,则返回false,否则返回true。对于特殊情况,代码还会尝试修正数组。
112

被折叠的 条评论
为什么被折叠?



