LeetCode 665. Non-decreasing Array (不递减数组)

时间:2023-12-21 15:13:20

Given an array 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 array[i] <= array[i + 1] holds for every i (1 <= i < n).

Example 1:

Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.

Example 2:

Input: [4,2,1]
Output: False
Explanation: You can't get a non-decreasing array by modify at most one element.

Note: The n belongs to [1, 10,000].


题目标签:Array

  题目给了我们一个nums array, 只允许我们一次机会去改动一个数字,使得数组成为不递减数组。可以实现的话,return true;不行的话,return false。

  这个题目关键在于,当遇见一个 nums[i] > nums[i+1] 的情况,我们是把 nums[i]降为nums[i+1] 还是 把nums[i+1]升为nums[i]。

  如果可行的话,当然是选择优先把 nums[i]降为nums[i+1],这样可以减少 nums[i+1] > nums[i+2] 的风险。

  来看一下两种情况:

  a. 1 3 5 4 6 7  -->  1 3 4 4 6 7

    当遇到5 > 4 的情况,这里因为4比5 之前的所有数字都大,所以可以把5 降为4。

  b. 1 4 5 3 6 7  -->  1 4 5 5 6 7

    当遇到5 > 3 的情况,这里3比5之前的4小,所以没有选择,只能把3 升为5。

  

  当需要第二次改动的时候,可以直接返回false,不需要把剩下的array走完。

Java Solution:

Runtime beats 89.68%

完成日期:10/20/2017

关键词:Array

关键点:了解有2种改动情况和优先级

 class Solution
{
public boolean checkPossibility(int[] nums)
{
boolean modified = false; for(int i=0; i<nums.length; i++)
{
if(i+1 < nums.length && nums[i] > nums[i+1])
{
if(modified) // if modified a number already
return false;
else // if it is first time to modify a number
{
if(i-1 < 0 || nums[i+1] >= nums[i-1]) // if nums[i+1] is larger or equal all numbers before nums[i]
nums[i] = nums[i+1]; // change nums[i] as same as nums[i+1]
else // if nums[i+1] is not larger than all numbers before nums[i]
nums[i+1] = nums[i]; // change nums[i+1] as same as nums[i] modified = true;
}
}
} return true; }
}

参考资料:N/A

LeetCode 题目列表 - LeetCode Questions List