https://leetcode.com/problems/non-decreasing-array/
Given an array nums 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 nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2).
Example 1:
Input: nums = [4,2,3] Output: true Explanation: You could modify the first 4 to 1 to get a non-decreasing array. (actually change 4 to 2 is fine too)Example 2:
Input: nums = [4,2,1] Output: false Explanation: You can't get a non-decreasing array by modify at most one element.Constraints:
1 <= n <= 10 ^ 4- 10 ^ 5 <= nums[i] <= 10 ^ 5优化循环过程,使得一次循环搞定
// O(n) O(1) class Solution { public: bool checkPossibility(vector<int>& nums) { int modified = 0; int n = nums.size(); int index; int indexOfNumsVal; for (int i = 0; i < n - 1; i++) { if (nums[i] > nums[i + 1]) { modified++; if (modified == 1) { if (i > 0 && nums[i - 1] > nums[i + 1]) { // 有前驱,且前驱比后继大,把后继改成i处的数值 index = i + 1; indexOfNumsVal = nums[i + 1]; nums[i + 1] = nums[i]; } else { // 没前驱,或者后继大于等于前驱,把i处的数值改成后继值 index = i; indexOfNumsVal = nums[i]; nums[i] = nums[i + 1]; } } else if (modified == 2) { nums[index] = indexOfNumsVal; return false; } } } if (modified > 0) nums[index] = indexOfNumsVal; return true; } };