This is the 8th day of my participation in Gwen Challenge

The topic of dry

Given an array of integers of length n, determine whether the array can become a non-decrement array with at most one element changed.

We define a nondecreasing sequence like this: for any I in the array (0 <= I <= n-2), nums[I] <= nums[I + 1].

Example 1:

Input: nums = [4,2,3] Output: true Explanation: You can make the first 4 a non-decreasing sequence by changing it to a 1.Copy the code

Greed

First of all, there are three cases, that is, our current cycle is at 1, and greater than 1, 1 and I >i-2, and greater than 1 and I <i-2(cannot be changed).

The original intention is actually to keep track of the values of the decrement interval, but the difference is that we have to change the contents of the original array, change the elements, and then determine, like

For 3423, we cannot directly decrement the number of the interval, but we need to judge it on the basis of the modified interval. 3423 is changed to 3443, and then we iterate backwards to find that there is still a decrement interval, and return false.

Execution time: 96 ms, beating 65.07% of all JavaScript commits

Memory consumption: 40.4 MB, beating 81.13% of all JavaScript commits

  var checkPossibility2 = function (nums) {
    let length = nums.length
    let decrementCount = 0
    for (let i = 1; i < length; i++) {
      if (nums[i] >= nums[i - 1]) {
        continue
      }
      decrementCount++;
      if (decrementCount > 1) return false
      if (i == 1) {
        nums[i - 1] = nums[i]
      } else if (i > 1) {
        if (nums[i] >= nums[i - 2]) {
          nums[i - 1] = nums[i]
        } else {
          nums[i] = nums[i - 1]}}}return true
  };
Copy the code