LeetCode-665. Non-decreasing Array [Non-decreasing Array]-Analysis and Code [Java]
1. Topic
Here is an integer array of length n. Please judge whether the array can be turned into a non-decreasing sequence when one element is changed at most.
We define a non-decreasing number sequence like this: For all i (0 <= i <= n-2) in the array, nums[i] <= nums[i + 1] is always satisfied.
Example 1:
输入: nums = [4,2,3]
输出: true
解释: 你可以通过把第一个4变成1来使得它成为一个非递减数列。
Example 2:
输入: nums = [4,2,1]
输出: false
解释: 你不能在只改变一个元素的情况下将其变为非递减数列。
Description:
- 1 <= n <= 10 ^ 4
- -10 ^ 5 <= nums[i] <= 10 ^ 5
Source: LeetCode
Link: https://leetcode-cn.com/problems/non-decreasing-array
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Two, analysis and code
1. Direct modification
(1) Thinking
Because only one element can be changed, a mark can be designed to record whether the change opportunity has been used. When making changes, make the changed elements as small as possible.
When nums[i-1]> nums[i], when the element needs to be changed, it can be divided into two cases:
- If i <2 or nums[i] >= nums[i-2], just change nums[i-1] to a number less than or equal to nums[i], because the judgment has already reached nums[i] at this time , So there is actually no need to operate;
- If i >= 2 and nums[i] <nums[i-2], you can only change nums[i] to num[i-1], and then make subsequent judgments.
(2) Code
class Solution {
public boolean checkPossibility(int[] nums) {
boolean changed = false;
for (int i = 1; i < nums.length; i++) {
if (nums[i - 1] > nums[i])
if (changed == false) {
if (i > 1 && nums[i] < nums[i - 2])
nums[i] = nums[i - 1];
changed = true;
}
else
return false;
}
return true;
}
}
(3) Results
Execution time: 1 ms, beating 99.54% of users
in all Java submissions ; memory consumption: 40.1 MB, beating 16.91% of users in all Java submissions.
Three, other
Nothing.