[LeetCode] 665. 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 one 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.

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:

  • n == nums.length
  • 1 <= n <= 104
  • -105 <= nums[i] <= 105

非递减数列。

给你一个长度为 n 的整数数组,请你判断在 最多 改变 1 个元素的情况下,该数组能否变成一个非递减数列。

我们是这样定义一个非递减数列的: 对于数组中所有的 i (0 <= i <= n-2),总满足 nums[i] <= nums[i + 1]。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/non-decreasing-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是贪心。虽然这只是一个数组题,但是出错的几率还是蛮大的。题意需要满足数组里面的 nums[i] <= nums[i + 1] ,只要有不满足的地方,就试着去调整,但是只能调整一处。不满足的时候,会发生nums[i] > nums[i + 1]。此时如果我们改哪个元素都有可能导致其他地方再出现不是递增的情况。比如当 nums[i] > nums[i + 1] 的时候,我们可以把 nums[i] 改大,或者把 nums[i + 1] 改小。无论是改大还是改小,有可能会影响input数组里面其他部分元素的关系。所以这里我们多看一个元素,当nums[i] > nums[i + 1],我们去看一下 nums[i - 2] 那个元素。这里贪心贪的是到底是把小的数字改大还是把大的数字改小。

  • 如果 nums[i - 2] <= nums[i] ,那么我们就把 nums[i - 1] 改小,使得 nums[i - 1] = nums[i]。因为之前一步的判断我们已经得出结论 nums[i] <= nums[i - 1],只有把 nums[i - 1] 再改小,才不会破坏左边已经判断出来的部分
  • 否则我们就把 nums[i] 改大,使得 nums[i] = nums[i - 1]

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public boolean checkPossibility(int[] nums) {
 3         int len = nums.length;
 4         int count = 0;
 5         for (int i = 1; i < nums.length; i++) {
 6             if (nums[i] < nums[i - 1]) {
 7                 count++;
 8                 if (i - 2 < 0 || nums[i - 2] <= nums[i]) {
 9                     nums[i - 1] = nums[i];
10                 } else {
11                     nums[i] = nums[i - 1];
12                 }
13             }
14         }
15         return count <= 1;
16     }
17 }

 

LeetCode 题目总结

posted @ 2021-02-07 04:16  CNoodle  阅读(139)  评论(0)    收藏  举报