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.
给一个数组,至多可以修改一个元素,使数组为不下降的数组,即从左到右每个元素<=后一个元素
思路:
最多修改一个元素,也就是nums[i] > nums[i+1]的情况最多出现一次。即出现一次以上时,直接返回false。
假设i = p时出现这种情况,
当p=0时,因为它左边没有元素,修改第一个元素即可。
p为倒数第二个元素,即p=n-2时,修改最后一个元素即可。
p在中间时,如果出现nums[p] > nums[p+1]
有两种选择,修改nums[p],或者修改nums[p+1]
修改nums[p]时要保证nums[p-1] <= nums[p+1],
修改nums[p+1]时要保证nums[p] <= nums[p+2],这样才能保证整体是升序的
注意最后没有出现nums[p] > nums[p+1]时也要返回true
public boolean checkPossibility(int[] nums) {
if(nums == null || nums.length == 0) {
return true;
}
int p = -1;
int n = nums.length;
for(int i = 0; i < n-1; i++) {
if(nums[i] > nums[i+1]) {
if(p >= 0) {
return false;
}
p = i;
}
}
//p<0即没有出现nums[p]>nums[p+1]这种情况
if(p <= 0 || p == n-2) {
return true;
}
return (nums[p-1] <= nums[p+1] || nums[p] <= nums[p+2]);
}
920



被折叠的 条评论
为什么被折叠?



